JAvaによるpropertiesファイルの読み書き
2598 ワード
内部システムはいつも1つのスイッチをして、パラメータは神馬を配置して、时にはpropertiesファイルでこれらの値を保存することができて、毎回修正してファイルに戻って、オンラインになる时このファイルを上書きしないでください、主要なコード.
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.*;
import java.util.Properties;
/**
* Property
* User: yfzhangbin
* Date: 13-8-7
* Time: 10:08
*/
public class PropertyEditor {
private String configFile; // appconfig.properties
private static Properties p = new Properties();
public void initProperties() { // init-method="initProperties" bean spring
InputStream in = null;
try {
Resource resource = new ClassPathResource(configFile);
in = resource.getInputStream();
p.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String read(String key, String defaultValue) {
return p.getProperty(key, defaultValue);
}
public Integer readInt(String key) {
return Integer.parseInt(read(key, "0"));
}
public void write(String key, Integer value) {
write(key, Integer.toString(value));
}
public void write(String key, String value) {
p.setProperty(key, value);
OutputStream out = null;
try {
Resource resource = new ClassPathResource(configFile);
out = new FileOutputStream(resource.getFile());
p.store(out, "write from web console");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
}