写入现有的 .txt 文件
Write in existing .txt file
如何写入现有的 .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());
}
}
但是它没有向文件中添加字符串,而是重新写入内部。
[更新]
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());
}
}
您必须以附加模式打开文件,这可以通过使用
FileWriter(String fileName, boolean append)
构造函数。
替换此行
FileOutputStream fOut = new FileOutputStream(file);
到
FileOutputStream fOut = openFileOutput("yourfile.txt", MODE_APPEND);
希望对您有所帮助。
如何写入现有的 .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());
}
}
但是它没有向文件中添加字符串,而是重新写入内部。
[更新]
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());
}
}
您必须以附加模式打开文件,这可以通过使用
FileWriter(String fileName, boolean append)
构造函数。
替换此行
FileOutputStream fOut = new FileOutputStream(file);
到
FileOutputStream fOut = openFileOutput("yourfile.txt", MODE_APPEND);
希望对您有所帮助。