**
Andriond Studio APP 在手机读写文件**
注意点:需要在Activity中引用并 注入上下文
package com.xwsoft.zthx.driver.common.util;
import android.app.Application;
import android.content.Context;
import org.jsoup.helper.StringUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
/**
* http 工具类
*/
public class PropertiesUtil extends Application {
/**
* 根据配置文件中的key获取value (当获取不到值赋予默认值)
*
* @return
*/
public String getPropertyByKey(String key) {
Properties props = new Properties();
try {
String fileName = "face.properties";
props.load(getApplicationContext().getAssets().open(fileName));
} catch (IOException e) {
e.printStackTrace();
}
String value = props.getProperty(key.trim());
if (StringUtil.isBlank(value)) {
value = "defaultValue";
}
return value.trim();
}
//初始化配置文件
//最好放在Application中,初始化。
public String initProperties() {
Properties props = new Properties();
try {
String fileName = "face.properties";
props.load(getApplicationContext().getAssets().open(fileName));
props.load(getApplicationContext().getAssets().open("face.properties"));
FileOutputStream out = getApplicationContext().openFileOutput("face.properties", Context.MODE_PRIVATE);
props.store(out, null);
} catch (Exception e) {
e.printStackTrace();
return "修改配置文件失败!";
}
return "设置成功";
}
/**
*
* @return
*/
public void setProperty(String key,String value) {
if(!value.isEmpty()){
try {
String path = "/assets/";
String fileName = "face.properties";
File file = new File(path, fileName);
OutputStream fos = new FileOutputStream(file);
Properties props = new Properties();
props.setProperty(key,value);
props.store(fos, "Update '" + key + "' value");
} catch (IOException e) {
System.err.println("属性文件更新错误");
}
}
}
}
|