Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append text to the end of the file

Tags:

android

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();
   }        
like image 900
mavzey Avatar asked Feb 14 '13 10:02

mavzey


People also ask

Which command to append the text at the end of the file?

Use the echo command, used with the append redirection operator, to add a single line of text to a file.

How do you append text?

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 .

How do you append data to a file?

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.


1 Answers

Try to set append boolean value to true in FileOutputStream:

outStream = new FileOutputStream(out, true);
outStreamWriter = new OutputStreamWriter(outStream); 
like image 100
Simon Dorociak Avatar answered Nov 05 '22 14:11

Simon Dorociak