Wednesday, 13 July 2016

How to append to a file in Java

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 the already existing file.

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. Here 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 because 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.

Appending to a file using BufferedOutputStream

In the 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. You can run this program twice to see that.

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");

 }
 /**
  * 
  * @param fileName
  */
 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();
   }
  }
 }

}

Appending to a file using BufferedWriter

In the 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. You can run this program twice to see that.

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();
  }
 }
}

Appending 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.

Using write() method

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.

Example code

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 provided as options varargs parameter which means appending to a file.

Using newBufferedWriter method

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.

Example Code

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

  1. How to read file from the last line in Java
  2. Reading file in Java using BufferedReader
  3. Zipping files in Java
  4. How to create PDF from XML using Apache FOP
  5. try-with-resources in Java 7

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment