本文主要讲述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编码】 } }
标签:java,String,配置文件,filePath,Properties,new,properties,读取 From: https://www.cnblogs.com/zwgitOne123/p/17036700.html