java的属性操作非常简单明了,用Properties类即可很简单的操作!
InputStream in = new FileInputStream(filename);
Properties pro = new Properties();
pro.load(in);
首先加载属性文件,当然除了可以使用InputStream外还可以使用Reader。
接下来就是用Properties类的一系列操作:
读指定的值:
public void readProperties(String key) {
System.out.println(pro.getProperty(key));
}
读全部的键值对:
public void readProperties() {
Enumeration em = pro.propertyNames();
while (em.hasMoreElements()) {
String key = (String) em.nextElement();
System.out.println(key + ": " + pro.getProperty(key));
}
}
写入属性:
public void writeProperties(String key, String value) {
pro.setProperty(key, value);
OutputStream out;
try {
out = new FileOutputStream(filename);
pro.store(out, key + " " + value);//键值对的存取方式
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
以上是比较常见的属性操作。
比较遗憾的是Properties文件不支持中文,因为它是以ISO8859-1字符编码进行存储的。
阅读(951) | 评论(0) | 转发(0) |