Radek
Radek

Reputation: 1413

writing to a text file in java

I have the following function for writing to a file:

public void writeToFile(String data) throws IOException {
    FileWriter fstream = null;


    try {
        fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(data);
        //Close the output stream
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fstream.close();
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

What it does every time it is called it creates a new file and writes a new line. What I want to achieve is to check whether file exist. If not create a new file and write something, if exists then open the file and add a new line without erasing existing text. How to do that?

Upvotes: 2

Views: 3785

Answers (3)

Jayendra
Jayendra

Reputation: 52769

FileWriter takes in an additional parameter for appends, which specifies if you want to create a new file or append to an existing file

fstream = new FileWriter("out.txt", true);

http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)

Upvotes: 2

Julian
Julian

Reputation: 1294

As there is a constructor in java's FileWriter class that can get an bool that idicates if the next "entry" is appended to the file, you should chage your

fstream = new FileWriter("out.txt");

to

fstream = new FileWriter("out.txt", true);

You can look up all those constructors in the java documentation: http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html

Upvotes: 0

mcfinnigan
mcfinnigan

Reputation: 11638

change your FileOutputStream constructor call to this:

fstream = new FileWriter("out.txt", true);

Upvotes: 6

Related Questions