String parameterValue) throws IOException {
Properties prop = new Properties();
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(fileNamePath);
// 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中
// in = propertiesTools.class.getResourceAsStream(fileNamePath);
prop.load(in);
out = new FileOutputStream(fileNamePath);
prop.setProperty(parameterName, parameterValue);
prop.store(out, parameterName);// 保存
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != in)
in.close();
if (null != out)
out.close();
}
}
public static void main(String[] args) throws IOException {
// 方法一:
// String fileNamePath = "info.properties";
// 上面不变,用类中注释掉的in =
// TestProperties.class.getResourceAsStream(fileNamePath);方法,必须要将.Properties文件和此
// class类文件放在同一个包中
// 方法二:
String fileNamePath = "config//info.properties";
// 这个方法需要在项目的要目录下建立config文件夹,然后把properties文件放在config下
// 取值
System.out.println("取username的值:" + getValue(fileNamePath, "username"));
System.out.println("取age的值:" + getValue(fileNamePath, "age"));
// 写值
setProperties(fileNamePath, "age", "21");
// 取此文件所有配置信息
readProperties(fileNamePath);
}
}