properties 文件操作
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 系统设置参数的读取和设置
* @author CodeToMyLaw
*
*/
public class SystemPropertiesUtils {
private static Properties properties = new Properties();
/**
* 初始化系统提供的参数
*/
private static void initProperties() {
InputStream in = null;
try {
String file = Thread.currentThread().getContextClassLoader().getResource("").getPath()+ "system.properties";
File f = new File(file);
in = new FileInputStream(f);
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 得到系统设置的参数
* @param key
* @return
*/
public static String getSystemParamValue(String key) {
initProperties();
String value = "";
if(properties != null) {
value = properties.getProperty(key);
}
return value;
}
/**
* 设置系统的参数
* @param key
* @param value
*/
public static void setSystemParamValue(String key,String value){
initProperties();
if(properties != null) {
properties.setProperty(key, value);
SystemPropertiesUtils s = new SystemPropertiesUtils();
String filename = s.getPath("system.properties");
try {
saveFile(filename,"Test");
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 保存到配置文件中
*
* @param filename
* @param description
* @throws Exception
*/
public static void saveFile(String filename, String description) throws Exception {
try {
File f = new File(filename);
FileOutputStream fileOutputStream = new FileOutputStream(f);
properties.store(fileOutputStream, description);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException ex) {
throw new Exception("无法保存指定的配置文件:" + filename);
}
}
/**
* 获取配置文件的路径(此方法是放置到src的目录下)
*
* @param fileName
* @return
*/
public String getPath(String fileName) {
return getClass().getClassLoader().getResource("").getPath() + fileName;
}
}