读文件
StringBuilder readFile(File file) {
StringBuilder builder = new StringBuilder();
try {
InputStream inStream = openFileInput(file.getName());
if (inStream != null) {
InputStreamReader inputReader = new InputStreamReader(inStream);
BufferedReader bufferedReader = new BufferedReader(inputReader);
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
builder.append("\n");// 读文件时貌似会丢失换行
}
} catch (Exception e) {
e.printStackTrace();
}
inputReader.close();
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return builder;
}
写文件
static boolean writeFile(String string, File dst) {
OutputStream out = null;
try {
out = new FileOutputStream(dst);
byte[] buf = string.getBytes();
out.write(buf, 0, buf.length);
out.flush();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
例如 读取
/data/data/<packageName>/files/aaa.json
并将其中的"left"全部替换为"right"
File file = new File(getApplicationContext().getFilesDir().getAbsolutePath(), "aaa.json");
StringBuilder builder = readFile(file);
String s = builder.toString().replace("\"left\"","\"right\"");
writeFile(s,file);
问题:
这里用string.getBytes()直接将String转换为byte数组,当内容很多时可能会抛出异常
其实我真正希望的效果是读取文件的某一行并编辑 然后重新写道这一行 但是网络上似乎没有这样效果的,只能先把文件内容先读出来 编辑 再写入
文件拷贝
/**
* copy asset file to app external storage data folder
*/
static boolean copyFile(File src, File dst) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.flush();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}