Reputation: 37
i using this function:
> 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());
> } }
i want to write a lot of times and every time i write it changes like deletes all and adds new thing i write but i do not want it to delete
husky thanks i do not know why you deleted your comment it works i changed to MODE_APPEND
another problem how do i do space in the text file
Upvotes: 1
Views: 1401
Reputation: 2260
Try this:
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);
}
}
}
Upvotes: 0
Reputation: 220
OutputStreamWriter by default overwrites. In order to append information to a file, you will have to give it additional information in the constructor. See also OutputStreamWriter does not append for more information.
Upvotes: 0
Reputation: 19700
Pass true
as the second argument to FileOutputStream
to open the file in append mode.
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream("mywords.txt", true), "UTF-8");
Upvotes: 2