因为最近遇到了,所以做个记录,方便以后使用
这是我项目目录:
properties文件
password=1234567
userName=qxf
读取和更新操作类
package com.read.properties;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author qxf
*/
public class ManageProperties {
/**
* 读取properties文件
*
* @param fileName 文件路径
* @return properties对象
*/
public Properties readProperties(String fileName) {
Properties properties = new Properties();
InputStream inputStream = getClass().getClassLoader().
getResourceAsStream(fileName);
if (inputStream != null) {
try {
properties.load(inputStream);
return properties;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return properties;
}
/**
* 修改properties文件
*
* @param properties properties对象
* @param fileName 文件路径
* @param value 需要修改的值
* @return 是否修改成功
*/
public boolean updateProperties(Properties properties, String fileName,
String[] value) {
String key = value[0];
String val = value[1];
properties.setProperty(key, val);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(fileName);
properties.store(fileOutputStream, "save success");
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public static void main(String[] args) {
String fileName = "userinfo.properties";
ManageProperties manageProperties = new ManageProperties();
Properties properties = manageProperties.readProperties(fileName);
System.out.println("userName: " + properties.get("userName"));
System.out.println("password: " + properties.get("password"));
String key = "password";
String val = "7654321";
String absolutePath = "src" + File.separator + "main" + File.separator +
"resources" + File.separator + fileName;
String[] value = {key, val};
boolean isSuccess = manageProperties.updateProperties(properties,
absolutePath, value);
if (isSuccess) {
System.out.println("update success");
} else {
System.out.println("update fail");
}
}
}
输出:
更新完成后的properties文件