利用JDK自带的Properties类即可操作属性文件,示例代码如下:
package com.test.properties;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class PropertiesDemo {
public String getValue(String fileName, String key) throws IOException {
Properties prop = new Properties();
InputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(fileName));
prop.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
String value = prop.getProperty(key);
return value;
}
public void writeProperties(String fileName, String key, String value) throws IOException {
Properties prop = new Properties();
OutputStream outputStream = null;
try {
// 将下边文件(example.properties)中的内容读出来,加入到fileName指定的文件中去
prop.load(new BufferedInputStream(new FileInputStream(
"E:/Workspace/MyEclipse6/examples/bin/cn/com/huixin/properties/example.properties")));
outputStream = new BufferedOutputStream(new FileOutputStream(fileName));
prop.put(key, value);
prop.setProperty("english", "95");
prop.store(outputStream, "Properties File Writen Test");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
}
public static void main(String[] args) {
PropertiesDemo demo = new PropertiesDemo();
String fileName1 = PropertiesDemo.class.getResource("example.properties").getPath();
String stuname;
try {
stuname = demo.getValue(fileName1, "stuname");
System.out.println("stuname=" + stuname);
} catch (IOException e) {
e.printStackTrace();
}
String fileName2 = PropertiesDemo.class.getResource("").getPath() + "example2.properties";
try {
demo.writeProperties(fileName2, "class", "3-5");
} catch (IOException e) {
e.printStackTrace();
}
}
}
示例中读取的example.properties文件的内容如下:
stuid = 25
stuname = \u767e\u5ea6
birthday = 2001-10-25
score = 89
生成的example2.properties文件的内容如下:
#Properties File Writen Test
#Sat Mar 24 22:32:01 CST 2012
english=95
stuname=\u767E\u5EA6
stuid=25
birthday=2001-10-25
class=3-5
score=89