Java读写配置文件——Properties类的简要使用笔记

时间:2023-03-09 13:27:29
Java读写配置文件——Properties类的简要使用笔记

任何编程语言都有自己的读写配置文件的方法和格式,Java也不例外。

在Java编程语言中读写资源文件最重要的类是Properties,功能大致如下:

1. 读写Properties文件
2. 读写XML文件
3. 不仅可以读写上述两类文件,还可以读写其它格式文件如txt等,只要符合key=value格式即可.
注意:资源文件中含有中文时的处理方法 
1. 将中文字符通过工作转成utf8编码,可以通过Java自带的nativetoascii或Eclipse中的属性编辑器。
2. 直接调用 new String(youChineseString.getBytes("ISO-8859-1"), "GBK");
附:WEB程序中加载资源文件的方法
Properties prop = null; 
1. prop = Thread.currentThread().getContextClassLoader().getResourceAsStream("filename");
2. prop = this.getClass().getClassLoader().getResourceAsStream("filename");
Properties类继承自Hashtable,大致API如下:
Java读写配置文件——Properties类的简要使用笔记
Java读写配置文件——Properties类的简要使用笔记
Java读写配置文件——Properties类的简要使用笔记
好了,直接用代码说话吧,这个类很容易使用
看下Demo目录结构:
Java读写配置文件——Properties类的简要使用笔记
先来个读取配置文件类:PropertiesReader.java
关于Properties读取文件这里提供六种方法:《JAVA读取Properties的六种方法》,下面取最常用的一种
关于路径的写法:(可以相对路径也可以是绝对路径)
Class.getResourceAsStream(String path) 
path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath(src文件)根下获取。
 package com.lcw.properties.test;

 import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties; /**
* properties文件读取类
*
*/
public class PropertiesReader { public void getPropertiesReader(){
Properties properties=new Properties();//获取Properties实例
InputStream inStream=getClass().getResourceAsStream("config.properties");//获取配置文件输入流
try {
properties.load(inStream);//载入输入流
Enumeration enumeration=properties.propertyNames();//取得配置文件里所有的key值
while(enumeration.hasMoreElements()){
String key=(String) enumeration.nextElement();
System.out.println("配置文件里的key值:"+key+"=====>配置文件里的value值:"+properties.getProperty(key));//输出key值
} } catch (IOException e) {
e.printStackTrace();
}
} }

再来个测试类:PropertiesTest.java

 package com.lcw.properties.test;

 public class PropertiesTest {

     /**
* 测试类
*/
public static void main(String[] args) {
PropertiesReader propertiesReader=new PropertiesReader();
propertiesReader.getPropertiesReader();
} }

这是配置文件信息:config.properties

color=black
animal=rabbit
food=hamburger
chinese=\u6211\u662F\u4E2D\u6587

看下运行效果:

Java读写配置文件——Properties类的简要使用笔记  

若要写入配置i文件也很简单,这里添加一个方法:

     //写入资源文件信息
public void writeProperties(){
Properties properties=new Properties();
try {
OutputStream outputStream=new FileOutputStream("config.properties");
properties.setProperty("number", "2015");
properties.setProperty("song", "手写的从前");
properties.store(outputStream, "rabbit");
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

生成文件:

#rabbit
#Wed Jan 07 17:16:56 CST 2015
number=2015
song=\u6211\u7231\u4F60