1. 需求
最近帮 Firmware组的同事写了一个打包工具,需要选择打包文件,为了保存上一次打开的目录,简单封装了一个类实现对Properties文件的简易读写。在一些对Properties文件读写有需求的小项目可以用到,不用为了一个不痛不痒的功能引入第三方jar包。
2. 代码
import java.io.*;
import java.util.Properties;
public class PropertiesConfig {
private final String configPath;
private final Properties config = new Properties();
public PropertiesConfig(String configPath) {
this.configPath = configPath;
}
/**
* 读取配置文件
* @throws IOException
*/
public void load() throws IOException {
Reader reader = null;
try {
reader = new FileReader(configPath);
this.config.load(reader);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 更新 properties 文件
* @param comment 注释,可传入 null
* @throws IOException
*/
public void save(String comment) throws IOException {
Writer writer = null;
try {
writer = new FileWriter(configPath);
config.store(writer, comment);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getProperty(String key) {
return this.config.getProperty(key);
}
public String getProperty(String key, String defaultV) {
return this.config.getProperty(key, defaultV);
}
public Object setProperty(String key, Object value) {
return this.config.setProperty(key, String.valueOf(value));
}
}
3. 使用
PropertiesConfig config = new PropertiesConfig("test.properties");
try {
config.load();
} catch (IOException e) {
e.printStackTrace();
}
String value = config.getProperty("key");
System.out.println(value);
config.setProperty("key", "new value");
try {
config.save("Hello");
} catch (IOException e) {
e.printStackTrace();
}
有需要可以加一些有用的方法,比如常用的getBoolean(key), getInteger(key)这种。