KeirDavis
KeirDavis

Reputation: 665

Read and write to file, but overwrites the file

I'm trying to figure out why this doesn't work. All the files which are shown actually exist. The 'logging.toString()' is a .txt file and it reads all the text in the logging and writes it back with the String which I want to be added. Although when I do this, it overwrites it. But I dont want that. Help?

    try{
        FileWriter fstream = new FileWriter(logging.toString());
        BufferedWriter out = new BufferedWriter(fstream);
        FileInputStream fstreams = new FileInputStream(logging);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstreams));
        String strLine;
        while ((strLine = br.readLine()) != null){
            htmlTextArea = htmlTextArea + strLine + "\n";
        }
        out.write(htmlTextArea + logto);
        out.close();
    } catch (Exception ex){}

Upvotes: 2

Views: 2314

Answers (4)

Ewald
Ewald

Reputation: 5751

Change this line

FileWriter fstream = new FileWriter(logging.toString());

to

FileWriter fstream = new FileWriter(logging.toString(), true);

That way, you tell Java you wish to APPEND the file. There's more in the Javadocs for FileWriter.

Upvotes: 2

Pshemo
Pshemo

Reputation: 124215

If you want to add something to file but not overwrite it use

FileWriter fstream = new FileWriter(logging.toString(),true);

Upvotes: 1

biziclop
biziclop

Reputation: 49714

Because that's the way FileWriter is implemented.

If you want to append, you should use a different constructor: new FileWriter( logging.toString(), true );

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160170

Why wouldn't it? You don't pass an append flag:

FileWriter(String filename, boolean append)

The API docs are your friend; they're often helpful for understanding behavior.

Upvotes: 4

Related Questions