我创建了一个文件,当我运行程序时,数据已写入文件,但是当我再次运行程序时,新数据会写入旧数据。 我需要一旦程序运行并收集数据,这些数据可以相互级联写入文件,而不会覆盖文件中的先前数据。
这段代码运行成功,但是当我再次运行程序时,我不需要写入过度写入,我需要将以前的数据保存在文件旁边,然后很快就将新数据写入。 编辑此代码后,它看起来像:
public class MainActivity extends Activity {
File file;
File sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FileName = "Output3.txt";
String eol;
OutputStream fos1;
FileWriter fw ;
BufferedWriter writer;
BufferedWriter bw ;
PrintWriter out;
EditText txtData;
Button btnWriteSDFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCard =getExternalFilesDir(null);
file = new File(sdCard,FileName);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
fos = new FileOutputStream(file);
myOutWriter =new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
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();
}
finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
please,can any one answer me?
答案 0 :(得分:1)
而不是使用OutputStreamWriter使用Filewriter FileWriter fileWritter = new FileWriter(file,true);当你传递真实时,它会附加内容。这个
FileWriter myOutWriter = new FileWriter(file.getName(),true);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.write(txtData.getText() + eol);// write this text.
writer.close();
fos.close();
答案 1 :(得分:1)
更改此行:
fos = new FileOutputStream(file);
要:
fos = new FileOutputStream(file, true);
这将打开文件,以便可以追加数据。
答案 2 :(得分:1)
使用
FileWriter writer = new FileWriter("yourfilename", true);
应传递第二个参数为true
将附加数据而不是覆盖
答案 3 :(得分:0)
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
// this changed bye fos = new FileOutputStream(myFile) to
fos = new FileOutputStream(myFile,true);
//FileWriter writer = new FileWriter("yourfilename", true);
myOutWriter = new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append("\n");
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
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();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
尽管我已经测试过它对我有用。