user1957902
user1957902

Reputation: 37

how to write to a text file without overwriting?

I am in a deadlock as to how to write the attributes in a form to a text file in java. I know there are many answers to this but i couldn't find any solution to the problem that i am facing. While there are many attributes in a form when i try writing them to a file it gets overwritten. Eg: there are 3 attributes when i try writing them to a file the third one overwrites the second one.

Here's what i have done so far:

writer = new PrintWriter(new FileWriter("C:/Documents and Settings/Administrator/Desktop/example1.txt"),true);
if(specific attr found)
    writer.println("my data");
writer.flush();
if(another found)
    writer.println("my data");
writer.flush();
if(third attr found)
    writer.println("my data");
writer.flush();
writer.close();

but its not working.

Upvotes: 1

Views: 2489

Answers (1)

Makky
Makky

Reputation: 17463

You can use FileUtils CommonsIO 2.4 API

Example

package com.doc;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Test {

    public static void main(String[] args) throws IOException {

        File file = new File("test.txt");
        FileUtils.write(file, "\n my data", true);
        FileUtils.write(file, "\n my data", true);
        FileUtils.write(file, "\n my data", true);

    }
}

output

 my data
 my data
 my data

Upvotes: 1

Related Questions