๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-append-to-file
Java append to file | DigitalOcean
August 3, 2022 - OutputStream os = new FileOutputStream(new File("append.txt"), true); os.write("data".getBytes(), 0, "data".length()); os.close(); Here is the final java append to file program showing all the different options we discussed above.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ java โ€“ append data to a file
Java โ€“ Append Data to a File | Baeldung
January 16, 2024 - Similarly, the FileOutputStream constructor accepts a boolean that should be set to true to mark that we want to append data to an existing file. Next โ€“ we can also append content to files using functionality in java.nio.file โ€“ which was ...
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ i/o โ€บ appending to a file in java
Appending to a File in Java
April 22, 2022 - To append content to an existing file, open the writer in append mode by passing the second argument as true. String textToAppend = "Happy Learning !!"; String fileName = "c:/temp/samplefile.txt"; try(FileWriter fileWriter = new FileWriter(fileName, ...
๐ŸŒ
Centron
centron.de โ€บ startseite โ€บ java append to file โ€“ tutorial
Appending Data to a File in Java โ€“ Best Methods
February 18, 2025 - We can also use PrintWriter to append to file in Java. ... File file = new File("append.txt"); FileWriter fr = new FileWriter(file, true); BufferedWriter br = new BufferedWriter(fr); PrintWriter pr = new PrintWriter(br); pr.println("data"); pr.close(); br.close(); fr.close(); You should use FileOutputStream to append data to file when itโ€™s raw data, binary data, images, videos etc.
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ append-data-fileoutputstream-java
How to Append Data to a File Using FileOutputStream in Java Without Overwriting Existing Data? - CodingTechRoom
FileOutputStream fos = new FileOutputStream("filename.txt", true); // 'true' for append mode. When using FileOutputStream to write data to a file in Java, the default behavior is to overwrite the existing content.
๐ŸŒ
JavaMadeSoEasy
javamadesoeasy.com โ€บ 2015 โ€บ 08 โ€บ program-to-append-to-file-using.html
JavaMadeSoEasy.com (JMSE): Program to Append to file using FileOutputStream in java file IO
For appending content in file, keep second parameter as true, using new FileOutputStream("c:/myFile.txt",true) will append content to file
๐ŸŒ
ZetCode
zetcode.com โ€บ java โ€บ appendfile
Java append to file - learn how to append to file in Java
It takes an optional second parameter, which determines whether the data is appended to the file. ... import java.io.FileOutputStream; import java.io.IOException; void main() throws IOException { String fileName = "src/main/resources/towns.txt"; byte[] tb = "ลฝilina\n".getBytes(); try (var fos = new FileOutputStream(fileName, true)) { fos.write(tb); } }
๐ŸŒ
Java Code Geeks
examples.javacodegeeks.com โ€บ home โ€บ java development โ€บ core java โ€บ io โ€บ fileoutputstream
Append output to file with FileOutputStream - Java Code Geeks
October 26, 2013 - Letโ€™s take a look at the code snippet that follows: package com.javacodegeeks.snippets.core; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class AppendOutputToFileWithFileOutputStream { public static void main(String[] args) { String s = "Java Code Geeks - Java Examples"; File file = new File("outputfile.txt"); FileOutputStream fos = null; try { fos = new FileOutputStream(file, true); // Writes bytes from the specified byte array to this file output stream fos.write(s.getBytes()); } catch (FileNotFoundException
Find elsewhere
Top answer
1 of 16
929

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

Java 7+

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(),
        StandardOpenOption.CREATE, StandardOpenOption.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:

  • The second parameter to the 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.)
  • 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.

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
}

Exception Handling

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
    }
}
2 of 16
203

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());
}
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ how to append text to a file in java
How to append text to a file in Java - Mkyong.com
October 1, 2020 - In Java, for NIO APIs like Files.write, we can use StandardOpenOption.APPEND to enable the append mode. For examples: // append a string to the end of the file private static void appendToFile(Path path, String content) throws IOException { ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 46843732 โ€บ append-to-same-file-using-fileoutput-stream
java - Append to Same file using fileoutput stream - Stack Overflow
I am using multiple methods to get data to be written to an .xlsx file. I am using HSSF for this. The first method creates a fileOutputStream and subsequent methods append to that stream and that is written to the file.
๐ŸŒ
Jenkov
tutorials.jenkov.com โ€บ java-io โ€บ fileoutputstream.html
Java FileOutputStream
August 28, 2019 - OutputStream output = new FileOutputStream("c:\\data\\output-text.txt"); There is a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append to the file or not.
๐ŸŒ
ZetCode
zetcode.com โ€บ java โ€บ fileoutputstream
Java FileOutputStream - writing to files in Java
January 27, 2024 - FileOutputStream(String name, boolean append) โ€” creates a file output stream to write to the file with the specified name; allows appending mode.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 567169 โ€บ java โ€บ append-object-FileOutputStream
How to append an object using FileOutputStream (I/O and Streams forum at Coderanch)
February 12, 2012 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums ยท this forum made possible by our volunteer staff, including ... ... I am using the following code to write an object to a file. However it seems that it overwrites an existing object and doesnt append it.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2012 โ€บ 12 โ€บ how-to-append-text-into-file-in-java-filewriter-example.html
How to append text into File in Java โ€“ FileWriter Example
Modified File Content: This data ... contents or bytes by using FileOutputStream, FileOutputStream(String path, boolean append) takes a boolean parameter to append into File, which will ensure that new bytes will be written ...
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2014 โ€บ 01 โ€บ how-to-append-to-a-file-in-java
How to append to a file in java using BufferedWriter, PrintWriter
Using this you can easily format the content which is to be appended to the File. import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo2 { public static void main( String[] args ) { try{ File file =new File("C://myfile.txt"); if(!file.exists()){ file.createNewFile(); } FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //This will add a new line to the file content pw.println(""); /* Below three statements would add three * mentioned Strings to the file in new lines.
๐ŸŒ
Tek-Tips
tek-tips.com โ€บ home โ€บ forums โ€บ software โ€บ programmers โ€บ languages โ€บ java
How to append information to an existing file - Java | Tek-Tips
November 23, 2007 - http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileOutputStream.html) So in your case, you might have: FileOutputStream out = new FileOutputStream(new File("log.txt"), true); And then use something like DataOutputStream to output. DataOutputStream dataOut = new DataOutputStream(out); ...