本文主要讲述java读取和写入properties文件操作
一. 介绍Properties类
Properties用于读取和写入Xx.properties文件,获取k-v
二. Properties类的读取和写入
Properties类的读取:
public class InoutProperties { public static void main(String[] args) { } @Test public void ReadProperties01() throws IOException { // 使用字符流读取【处理流】 String filePath = "src\\mysql.properties"; BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath)); String str = bufferedReader.readLine(); HashMap<String, String> hashMap = new HashMap<>(); while(str != null && !str.equals("")){ String[] splits = str.split("="); hashMap.put(splits[0],splits[1]); str = bufferedReader.readLine(); } // 遍历hashmap Set<Map.Entry<String, String>> entrySet = hashMap.entrySet(); for (Map.Entry<String, String> entry : entrySet) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } @Test public void ReadProperties02() throws IOException{ // 使用Properties类读取文件 String filePath = "src\\mysql.properties"; // 1.创建对象 Properties properties = new Properties(); // 2.加载节点流 properties.load(new FileReader(filePath)); // 3.k-v结果显示到控制台 properties.list(System.out); // 4.根据key获取value String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); System.out.println("用户: " + user + "密码: " + pwd); } }
Properties类的写入:
public class OutInProperties { public static void main(String[] args) throws IOException { String filePath = "src\\mysql1.properties"; Properties properties = new Properties(); properties.setProperty("charset","utf-8"); properties.setProperty("user","汤姆"); // properties.store(new FileWriter(filePath),null); 【存储的是汉字】 properties.store(new FileOutputStream(filePath),null); // 【存储的是汉字的unicode编码】 } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/98955.html