Properties文件保存软件配置信息,类似hashmap保存信息,key和value对应。在网上找了一个封装类,使用起来特别方便
- 封装类ProperUtil
package com.softconfig.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
/**
* Created by ${王sir} on 2017/6/23.
* application
*/
public class ProperUtil {
private static String FilePath = "/sdcard/.Properties/";
private static String FileName = ".investigation_terminal.properties";
/**
* 得到properties配置文件中的所有配置属性
*
* @return Properties对象
*/
public static String getConfigProperties(String key) {
File mfile = new File(FilePath);
if (!mfile.exists()) {
mfile.mkdirs();
}
File mfileName = new File(FilePath+FileName);
if (!mfileName.exists()) {
return "";
}
Properties props = new Properties();
InputStream in = null;
try {
in = new FileInputStream(FilePath+FileName);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
String value = props.getProperty(key);
if (value==null) {
value="";
}
return value;
}
/**
* 给属性文件添加属性
*
* @param value
* @author qiulinhe
* @createTime 2016年6月7日 下午1:46:53
*/
public static void writeDateToLocalFile( String key, String value) {
File mfile = new File(FilePath);
if (!mfile.exists()) {
mfile.mkdirs();
}
Properties p = new Properties();
try {
InputStream in = new FileInputStream(FilePath+FileName);
p.load(in);
} catch (IOException e) {
e.printStackTrace();
}
p.put(key, value);
OutputStream fos;
try {
fos = new FileOutputStream(FilePath+FileName);
p.store(fos, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
FilePath是文件保存路径。FileName是保存文件的名称
- 运用
将信息保存到文件中
Sting testContent = "测试内容";
ProperUtil.writeDateToLocalFile("TEST", testContent);
获取保存的信息
String testContent = ProperUtil.getConfigProperties("TEST");
用起来特别方便。记得权限别忘记添加
<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />