【发布时间】:2015-12-29 07:24:39
【问题描述】:
我使用代码将字符串插入到文件中。但是,该代码仅支持在文件的最后一行插入。你能帮我把它改成在android的第一行字符串写一个字符串吗?这些字符串由 line.separator 分隔
例如: 文件中的当前字符串
aaa
bbb
ccc
如果新字符串是“111”,请将其插入
111
aaa
bbb
ccc
这是我的代码
private void writeTextFile(String filecontent)
{
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + "/" + "filentxt.txt" ;
FileOutputStream fop = null;
File file = null;
try {
file =new File(filename);
fop=new FileOutputStream(file,true);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
filecontent=filecontent+ System.getProperty ("line.separator");
// get the content in bytes
byte[] contentInBytes = filecontent.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
我看到了,但它使用了其他方式,例如 RandomAccessFile
-
@Boss:它使用了一个临时文件并在使用后将其删除。我认为这不是很好的方法
-
读取文件内容并在追加数据后写入
标签: android file fileoutputstream android-file