I am using the below code segment to write text to the end o the file for each time it is called. But, it is erasing the old data and then writes the new data to the beginning of the file. How can I fix the below code so that it is append new data always end of the file ?
public boolean writeToFile(String directory, String filename, String data ){
File out;
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;
out = new File(new File(directory), filename);
if ( out.exists() == false ){
out.createNewFile();
}
outStream = new FileOutputStream(out) ;
outStreamWriter = new OutputStreamWriter(outStream);
outStreamWriter.append(data);
outStreamWriter.flush();
}
Use the echo command, used with the append redirection operator, to add a single line of text to a file.
Position the cursor in your document where you want to append the text. Select the Insert tab, and from the Text group, select Object . Select Text from File from the drop-down list. Select the file and select Insert .
If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as true . If the number of write operations is huge, you should use the BufferedWriter. To append binary or raw stream data to an existing file, you should use FileOutputStream.
Try to set append boolean
value to true in FileOutputStream
:
outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With