Java操作Properties文件

利用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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章