views:

496

answers:

2

I need to append text repeatedly to an existing file in Java. How do I do that?

+11  A: 

Are you doing this for logging purposes? If so Apache Log4j is the de facto standard Java logging library.

If you just want something simple, this will work:

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //oh noes!
}

The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file). Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out. But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Kip
+9  A: 

You can use fileWriter with a true for appending.

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}
northpole