I need to append text repeatedly to an existing file in Java. How do I do that?
Using PrintWriter PrintWriter implements all of the print() methods found in PrintStream , so we can use all formats which you use with System. out. println() statements. To append content to an existing file, open the writer in append mode by passing the second argument as true .
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
For a one-time task, the Files class makes this easy:
try { Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND); }catch (IOException e) { //exception handling left as an exercise for the reader }
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE
and APPEND
options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException { Files.writeString( Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"), s + System.lineSeparator(), CREATE, APPEND ); }
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter
is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println("the text"); //more code out.println("more text"); //more code } catch (IOException e) { //exception handling left as an exercise for the reader }
Notes:
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)BufferedWriter
is recommended for an expensive writer (such as FileWriter
).PrintWriter
gives you access to println
syntax that you're probably used to from System.out
.BufferedWriter
and PrintWriter
wrappers are not strictly necessary.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 }
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter("myfile.txt", true); bw = new BufferedWriter(fw); out = new PrintWriter(bw); out.println("the text"); out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } finally { try { if(out != null) out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } try { if(bw != null) bw.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } try { if(fw != null) fw.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } }
You can use fileWriter
with a flag set to 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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With