Organizational Research By

Surprising Reserch Topic

How to append text to an existing file in Java


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

asked Jun 18, 2015 in Core java by rajesh
0 votes
86 views



Related Hot Questions

1 Answer

0 votes

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

If you just want something simple, this will work:

Java 7

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
    out.println("the text");
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Older Java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Notes:

  • The second parameter to the¬†FileWriter¬†constructor will tell it to append to the file (as opposed to writing a new file).
  • Using a¬†BufferedWriter¬†is recommended for an expensive writer (such as¬†FileWriter).
  • 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.
answered Jun 18, 2015 by rajesh

...