我创建了一个文件,当我运行程序时,数据被写入文件中,但是当我再次运行程序时,新数据会覆盖旧数据。 我需要一旦程序运行并收集数据,这些数据就可以依次写入文件中,而不会覆盖文件中以前的数据。
这段代码运行成功,但是当我再次运行程序时,会发生覆盖写入,而我不需要这样做,我需要将以前的数据保存在文件中,并很快在文件旁边写入新数据。
public class MainActivity extends Activity {
File file;
String sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FlieName = "Output1.txt";
EditText txtData;
Button btnWriteSDFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
file = new File("/sdcard/Output1.txt");
file.createNewFile();
fos = new FileOutputStream(file);
String eol = System.getProperty("line.separator");
myOutWriter =new OutputStreamWriter(fos);
myOutWriter.append(txtData.getText() + eol);// write from editor
myOutWriter.close();
fos.close();
Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
最佳答案
首先,您调用createNewFile()
。这表明您要创建一个新文件。如果您不想创建新文件,请不要调用createNewFile()
。而且,由于 createNewFile()
的文档说“此方法通常没有用”,因此您可能希望考虑删除它。
其次,您需要在打开和使用该文件时表明您想要附加到现有数据。 standard recipe为此:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
FileWriter
构造函数的第二个参数中的 true
表示您要追加而不是覆盖。
第三,不要在 Android 中对路径进行硬编码。 /sdcard/Output1.txt
多年来一直表现不佳,无法在某些 Android 设备上运行。
第四,不要弄乱外部存储的根目录。因此,而不是:
file = new File("/sdcard/Output1.txt");
用途:
file = new File(getExtenalFilesDir(null), "Output1.txt");
将文件放入您自己的应用程序特有的子目录中。
关于java - 如何在不覆盖预先保存的数据的情况下向文件中写入更多内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17764160/