- Properties 有点类似 Android 中的 SP。
- Properties 创建一个文件,然后对文件进行读写操作。
具体操作
1. 创建工具类
public class PropertiesUtil {
private static final String PROP_PATH = 文件路径+文件名;
/**
* 得到config.properties配置文件中的所有配置属性
*
* @return Properties对象
*/
public static Properties loadConfig() {
Properties properties = new Properties();
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(PROP_PATH);
properties.load(inputStream);
} catch (Exception e) {
LogUtil.e(e);
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LogUtil.e(e);
}
}
}
return properties;
}
/**
* 保存配置文件
*/
public static void saveConfig(Properties properties) {
FileOutputStream outputStream = null;
try {
File fil = new File(PROP_PATH);
if (!fil.exists()) {
fil.createNewFile();
}
outputStream = new FileOutputStream(fil);
properties.store(outputStream, "");
} catch (Exception e) {
LogUtil.e(e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
LogUtil.e(e);
}
}
}
}
}
2. 工具类的使用
//取数据
Properties properties = PropertiesUtil.loadConfig();
String value = properties.getProperty("key");
//存数据
Properties properties = properties = new Properties();
properties.put("key", value);
PropertiesUtil.saveConfig(properties);