In the post writing file in Java we have already seen how to write to a file in Java but the code given there creates a new file every time and writes the lines in the file. But there are many cases when you actually want to append to an already existing file in Java.
In this post we’ll see how to append to a file in Java. Both FileOutputStream and FileWriter classes have a constructor with a boolean argument, which when passed as true, means appending to a file. FileOutputStream and FileWriter are classes provided by Java to write files using byte stream and character stream respectively but using them directly will slow down the I/O operation considerably.
It is always advisable to use BufferedOutputStream or BufferedWriter rather than directly using FileOutputStream and FileWriterbecause that will provide buffering to the output streams and won't cause a call to the underlying system for each byte written. Buffered output streams write data to a buffer, and the native output API is called only when the buffer is full, making I/O operation more efficient.
Java program to append to a file using BufferedOutputStream
In the Java code if the file is not existing already it will be created and lines will be written to it. If it already exists then lines will be appended to that file.
import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class FileAppend { public static void main(String[] args) { // Change path for windows writeFile("/home/netjs/Documents/text.txt"); } public static void writeFile(String fileName){ FileOutputStream fos; BufferedOutputStream bos = null; try { fos = new FileOutputStream(fileName, true); bos = new BufferedOutputStream(fos); // For windows you may need /r/n for new line bos.write("Writing first line\n".getBytes()); bos.write("Writing second line\n".getBytes()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(bos != null){ bos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Java program to append to a file using BufferedWriter
BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing.
When appending, if the file does not exist already it will be created and lines will be written to it. If it already exists then lines will be appended to that file.
import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; public class FileAppendWrite { public static void main(String[] args) { //Change path for windows writeFile("/home/netjs/Documents/test.txt"); } /** * * @param fileName */ public static void writeFile(String fileName){ // Using Java 7 try-with-resources try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName, true))){ bw.write("Writing first line"); bw.newLine(); bw.write("Writing second line"); bw.newLine(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
Java program to append to a file using Files class methods
In Java 7 Files class is added which provides write() method to write to a file. There is also a newBufferedWriter method with 2 arguments, added in Java 8 that can be used to write to a file. In both of these methods you can pass StandardOpenOption.APPEND as option argument when you want to append to a file in Java.
There are 2 overloaded versions of write method.
- public static Path write(Path path, byte[] bytes,OpenOption... options) throws IOException– Write bytes to a file specified by the path. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. For appending to a file you need to provide StandardOpenOption.APPEND.
- public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException- Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system propertyline.separator. Characters are encoded into bytes using the specified charset.
Appending to a file using Files.write() method
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileWrite8 { public static void main(String[] args) { String content = "This is the line to be added.\nThis is another line."; try { Files.write(Paths.get("G://test.txt"), content.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Here note that String is converted to Byte array and also StandardOpenOption.APPEND is passed as options varargs parameter which means appending to a file.
- Refer Writing file in Java to see how to write to a file using Files class methods.
There are 2 overloaded versions of newBufferedWriter method.
- public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException- Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner. Options parameter specifies whether new file is created for writing or bytes are appended to an already existing file. For appending to a file you need to provide StandardOpenOption.APPEND.
- public static BufferedWriter newBufferedWriter(Path path, Charset cs,OpenOption... options) throws IOException- Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner. Here path is the path to the file, cs is the charset to use for encoding and options parameter specifies how the file is opened.
Appending to a file using Files.newBufferedWriter method
import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileWrite8 { public static void main(String[] args) { Path path = Paths.get("G://test.txt"); try (BufferedWriter writer = Files.newBufferedWriter(path, StandardOpenOption.APPEND)) { writer.write("Hello World"); writer.newLine(); writer.write("Hello again"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Here note that StandardOpenOption.APPEND is provided as options varargs which means appending to a file.
That's all for this topic How to Append to a File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-