如题:如果我们在src下新建一个配置文件test.properties文件后需要读取,并且修改;代码如下
public class TestClass {
static TestClass te = new TestClass();
public static void main(String[] args) throws IOException {
InputStream in = null;
in = te.getClass().getClassLoader().getResourceAsStream("test.properties");
Properties p = new Properties();
p.load(in);
in.close();
System.out.println(p.getProperty("name"));
updateProperties("name","update");
}
public static void updateProperties(String keyname,String keyvalue) {
try {
URL url = te.getClass().getClassLoader().getResource("test.properties");
String filePath = url.getPath();
OutputStream fos = new FileOutputStream(filePath);
Properties props = new Properties();
props.setProperty(keyname, keyvalue);
props.store(fos, keyname);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
备注:
我们在修改test.properties文件时,其实修改的是运行环境中的test.properties文件,
即java工程中bin目录下的test.properties文件,而并不是src下的test.properties文件!