如何在现有的.txt文件中书写?我尝试了多种方法,我已经停止了这个方法:
private void writeToFile(String data) {
try {
File file = new File(infoDirectory, txtName);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
Log.i("Debug", "File write failed: " + e.toString());
}
}
但不是在文件中添加字符串,而是重写内部。
[UPDATE]
private void writeToFile(String data) {
try {
File file = new File(infoDirectory, txtName);
FileWriter append = new FileWriter(file, true);
BufferedWriter output = new BufferedWriter(append);
output.write(data);
}
catch (IOException e) {
Log.i("Debug", "File write failed: " + e.toString());
}
}
[工作代码]
private void writeToFile(String data) {
try {
File file = new File(infoDirectory, txtName);
FileOutputStream fOut = new FileOutputStream(file,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
Log.i("Debug", "File write failed: " + e.toString());
}
}
答案 0 :(得分:1)
您必须以附加模式打开文件,这可以通过使用
来实现 FileWriter(String fileName, boolean append)
构造函数。
替换此行
FileOutputStream fOut = new FileOutputStream(file);
要
FileOutputStream fOut = openFileOutput("yourfile.txt", MODE_APPEND);
希望它有所帮助。