我使用代码在文件中插入一个字符串。但是,该代码仅支持在文件的最后一行插入。你能帮我改一下,在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();
}
}
答案 0 :(得分:0)
在文件开头
使用RandomAccessFile
进行写入
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + "/" + "filentxt.txt" ;
RandomAccessFile f = new RandomAccessFile(new File(filename), "rw");
f.seek(0); // to the beginning
f.write("111".getBytes());
f.close();