Add Text to Existing txt. File in JAVA?

Hey guys I want to be able to add lines of text to a text file without overriding the whole file in Java?

My friend you are going to want to open the file for 'appending' instead of 'writing'. Appending will add lines, whereas writing writes over the current stuff.

1 Like

thanks, got any good examples?

1 Like

Source is from Stackoverflow <---- love this site btw

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.