前言:以下一读一写两个方法都是从“E家”总结而来,很容易看,也很容易用,将里面的路径换成自己的,就可以了。
/**
* 读取模块CubeModule.json
* @param m
* @return
*/
public String readCubeModuleJson(CubeModule m) {
if (m == null) return null;
String result = null;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File s = new File(URL.HtmlPath + "/" + m.getIdentifier() + "/CubeModule.json");
try {
FileInputStream in = new FileInputStream(s);
// 获取文件的字节数
int lenght = in.available();
// 创建byte数组
byte[] buffer = new byte[lenght];
// 将文件中的数据读到byte数组中
in.read(buffer);
result = EncodingUtils.getString(buffer, "UTF-8");
} catch (Exception e) {
Log.i("模块", e.getMessage());
}
}
return result;
}
/**
* 写文件。
*
* @param json
* @return
*/
public boolean writeToJsonFile(String identifier, String json) {
Boolean flag = false;
// 获取sd卡目录
File file = null;
OutputStream output = null;
try {
file = new File(URL.HtmlPath + "/" + identifier + "/");
if (!file.exists()) {
file.mkdirs(); // 创建文件夹
}
file = new File(URL.HtmlPath + "/" + identifier + "/CubeModule.json");
output = new FileOutputStream(file);
output.write(json.getBytes());
output.flush();
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}