本文最后更新于:December 3, 2021 pm
积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里,不积小流无以成江海。齐骥一跃,不能十步,驽马十驾,功不在舍。面对悬崖峭壁,一百年也看不出一条裂缝来,但用斧凿,能进一寸进一寸,能进一尺进一尺,不断积累,飞跃必来,突破随之。
目录
Java集合库提供了一个Properties来表示一组“配置”。由于历史遗留原因,Properties内部本质上是一个Hashtable,但我们只需要用到Properties自身关于读写配置的接口。配置文件的特点是,它的Key-Value一般都是String-String类型的。
1.读取配置文件
用Properties读取配置文件,一共有三步:
- 创建Properties实例;
- 调用load()读取文件;
- 调用getProperty()获取配置。
调用getProperty()获取配置时,如果key不存在,将返回null。我们还可以提供一个默认值,这样,当key不存在的时候,就返回默认值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| url = "www.tothefor.com" author = "dragonone" date = "234324" name = "tothefor"
String file = "src/main/data.properties"; Properties pro = new Properties(); pro.load(new FileInputStream(file)); String url = pro.getProperty("url"); String age = pro.getProperty("age","123"); System.out.println(url); System.out.println(age);
"www.tothefor.com" 123
|
2.写入配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| String file = "src/main/java/com/propreties/data.properties"; Properties pro = new Properties(); pro.load(new FileInputStream(file)); pro.setProperty("url2", "www.tothefor.com"); pro.setProperty("language", "Java"); pro.store(new FileOutputStream("src/main/java/com/propreties/data.properties"), "two commit");
#two commit #Thu Aug 05 16:41:21 CST 2021 url="www.tothefor.com" date="234324" name="tothefor" author="dragonone" url2=www.tothefor.com language=Java
Properties pro = new Properties(); pro.setProperty("url2", "www.tothefor.com"); pro.setProperty("language", "Java"); pro.store(new FileOutputStream("src/main/java/com/propreties/data1.properties"), "two commit");
#two commit #Thu Aug 05 16:43:46 CST 2021 url2=www.tothefor.com language=Java
|
3.中文乱码解决
3.1 读取中文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #two commit #Thu Aug 05 16:41:21 CST 2021 url="www.tothefor.com" date="234324" name="tothefor" author="dragonone" url2=www.tothefor.com language=Java test = 中文状态
String file = "src/main/java/com/propreties/data.properties"; Properties pro = new Properties(); InputStream in = new BufferedInputStream(new FileInputStream(file)); pro.load(new InputStreamReader(in)); String url = pro.getProperty("test"); String age = pro.getProperty("age","123"); System.out.println(url); System.out.println(age);
中文状态 123
|
3.2 写入中文
| String file = "src/main/java/com/propreties/data1.properties"; Properties pro = new Properties();
pro.setProperty("testinch","测试写入中文"); FileOutputStream oFile = new FileOutputStream(file,true); pro.store(new OutputStreamWriter(oFile, "utf-8"), "lll");
#lll #Thu Aug 05 17:10:19 CST 2021 testinch=测试写入中文
|