package com.example.demo.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesManager {
private Properties properties;
private File file;
private PropertiesManager() {
getProperties();
}
public PropertiesManager(String fileName) {
this(new File(fileName));
}
public PropertiesManager(File file) {
this();
if (!(file != null && file.exists() && file.isFile() && file.getName().endsWith(".properties"))) {
throw new IllegalArgumentException("无效文件!");
}
this.file = file;
try {
properties.load(new FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public Properties getProperties() {
if (properties != null) {
return properties;
} else {
properties = new Properties();
}
return properties;
}
public Object setProperty(String key, String value) {
return properties.setProperty(key, value);
}
public Properties set(String key, String value) {
properties.setProperty(key, value);
return this.properties;
}
public boolean flush() {
return flush("");
}
public boolean flush(String desc) {
try {
properties.store(new FileOutputStream(file), desc);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
使用方法:
String fileName = "application.properties";
PropertiesManager propertiesManager = new PropertiesManager(fileName);
propertiesManager.setProperty("dataSourceFilePath", "E:\\dev\\aria2\\aria2\\log.txt");
// propertiesManager.set("key1","value2").set("key2","value2").flush();
propertiesManager.flush();