2

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?

2
  • isFile() returns true if the file exists, and false if not.
    – Waltzy
    Oct 6, 2011 at 9:52
  • Or save yourself some code: com.google.common.io.Files.append(CharSequence, File, Charset)
    – artbristol
    Oct 6, 2011 at 9:55

3 Answers 3

6

change your FileOutputStream constructor call to this:

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

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)

1
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.