IO.png
/**
* 读取InputStream
*
* @param is 输入流
* @return 流转化的字符串
* @throws IOException IO异常
*/
private static String read(InputStream is) throws IOException {
byte[] temp = new byte[1024];
int len = 0;
StringBuilder sb = new StringBuilder("");
while ((len = is.read(temp)) > 0) {
sb.append(new String(temp, 0, len));
}
return sb.toString();
}
/**
* 写入OutputStream
*
* @param os 输出流
* @param fileContent 文本内容
*/
private void write(OutputStream os, String fileContent) {
try {
if (fileContent != null) {
os.write(fileContent.getBytes());
}
close(os);//关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 关闭可关闭对象
*
* @param io 可关闭对象
*/
private void close(Closeable io) {
if (io != null) {
try {
io.close();
} catch (IOException e) {
L.e(e);
}
}
}
//写入数据 追加模式在/data/data/com.toly1994.sii_file/files文件家下创建writeInLocal.txt,内容"toly"
fileHelper.writeInLocal(this, "writeInLocal.txt", "toly", true);
//写入数据 覆盖模式在/data/data/com.toly1994.sii_file/files文件家下创建writeInLocal_2.txt,内容"toly"
fileHelper.writeInLocal(this, "writeInLocal_2.txt", "toly", false);
writeInLocal.png
String data = fileHelper.readInLocal(this, "writeInLocal.txt");
Log.e(TAG, data);//tolytolytoly
/**
* 在data/data/本包中写入文件:追加文件模式
*
* @param fileName 文件名
* @param fileContent 文件内容
* @param append 是否以追加模式
*/
public void writeInLocal(Context ctx,String fileName, String fileContent,boolean append) {
FileOutputStream fos = null;
try {
fos = ctx.openFileOutput(fileName, append?Context.MODE_APPEND:Context.MODE_PRIVATE);
write(fos, fileContent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
close(fos);
}
}
/**
* 在data/data/本包中读取文件
*
* @param fileName 文件名
* @return 文件内容
*/
public String readInLocal(Context ctx,String fileName) {
FileInputStream fis = null;
String result = null;
try {
fis = ctx.openFileInput(fileName);
result = read(fis);
//关闭输入流
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fis);
}
return result;
}
assets.png
String assetsData = fileHelper.readInAssets(this, "act.json");
Log.e(TAG, assetsData);//{"name":"toly"}
/**
* //////////////////////////从assets 中读取文件/////////////
*
* @param fileName 文件名
* @return 文件内容
*/
public String readInAssets(Context ctx,String fileName) {
InputStream is = null;
String result = null;
try {
is = ctx.getAssets().open(fileName);
result = read(is);
//关闭输入流
is.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is);
}
return result;
}
本文由张风捷特烈原创,转载请注明 更多安卓技术欢迎访问:https://www.jianshu.com/c/004f3fe34c94 张风捷特烈个人网站,编程笔记请访问:http://www.toly1994.com 你的喜欢与支持将是我最大的动力