Android开发存储配置信息的方式很多,properties是其中一种,但是不常用。有一个需求可能要用到,所以整理了一个工具类
配置文件存放位置:src/assets文件夹或者Res/Raw文件夹下
import android.content.Context;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import cn.gov.bjchfp.syz.R;
/**
* User: ksee(wosyou@qq.com)
* http://eekidu.github.io/
* Date: 2016/8/19.
* Desc:
*/
public class PropertiesUtils {
/*getApplicationContext().getFilesDir().getAbsolutePath(); */
public static final String PATH = "GlobalValue.File_PATH+'/login.properties'";
/**
* 1.得到Assets文件夹下的配置文件
*
* @param context
* @return
*/
public static Properties getsAssetsConfigs(Context context, String proName) {
Properties props = new Properties();
try {
InputStream in = context.getAssets().open(proName);
props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
/**
* 2.得到Raw文件夹下的配置文件
*
* @param context
* @return
*/
public static Properties getRawConfig(Context context, String proName) {
Properties props = new Properties();
try {
InputStream in = context.getResources().openRawResource(R.raw.config);
props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
/**
* 3.不需要上下文获得配置文件
*
* @return
*/
public static Properties getConfigs() {
Properties pro = new Properties();
InputStream resourceAsStream = PropertiesUtils.class.getResourceAsStream("/assets/config.properties");
try {
pro.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
return pro;
}
/**
* 保存配置到本地配置文件
*
* @param key
* @param value
*/
public void put(String key, String value) {
Properties p = new Properties();
try {
InputStream in = new FileInputStream(PATH);
p.load(in);
} catch (IOException e) {
e.printStackTrace();
}
p.setProperty(key, value);
OutputStream fos;
try {
fos = new FileOutputStream(PATH);
p.store(fos, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}