读写配置文件
代码块如下:
package util;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
private static Properties pro = new Properties();
static{
try {
InputStream is = new BufferedInputStream(new FileInputStream("config/database.properties"));
pro.load(is); //将配置文件列表,放在对象pro中;
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//获得键 key 对应的值
public static String getProperty(String key){
return pro.getProperty(key);
}
//设置或添加配置文件
public static void setProperty(String key, String value){
try {
FileOutputStream fos = new FileOutputStream("config/database.properties");
pro.setProperty(key, value);
pro.store(fos, "update "+key+":"+ value);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//测试
public static void main(String[] args) {
ReadProperties.setProperty("password", "aaa");
System.out.println(ReadProperties.getProperty("password"));
System.out.println("dd");
}
}
注释:
1,类Properties继承了 java.util.Map,里面的getProperty(k), 和setProperty(k, v)和map的 put()方法类似;
2,代码 pro.load(is) 表示将 配置文件中的键值对 保存到Properties的对象中;
3,static 代码块 在类初始化的时候会执行, 并且只会执行一次;