我使用这个功能:
> private void writeToFile(String data) {
> try {
> OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("mywords.txt",
> Context.MODE_PRIVATE));
> outputStreamWriter.write(data);
> outputStreamWriter.close();
> }
> catch (IOException e) {
> Log.e("Exception", "File write failed: " + e.toString());
> } }
我想写很多次,每次我写它改变就像删除所有并添加我写的新东西但我不想删除
哈士奇谢谢我不知道为什么你删除你的评论它有效我改为MODE_APPEND
另一个问题我如何在文本文件中做空间
答案 0 :(得分:2)
将true
作为第二个参数传递给FileOutputStream
,以附加模式打开文件。
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("mywords.txt", true), "UTF-8");
答案 1 :(得分:0)
默认情况下,OutputStreamWriter会覆盖。为了将信息附加到文件,您必须在构造函数中提供其他信息。有关详细信息,另请参阅OutputStreamWriter does not append。
答案 2 :(得分:0)
试试这个:
private void writeToFile(String data) {
File file = new File("mywords.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, true);
// Writes bytes from the specified byte array to this file output stream
fos.write(data.getBytes());
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while writing file " + ioe);
}
finally {
// close the streams using close method
try {
if (fos != null) {
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
}