March 16, 2022

How to Append to a File in Java

In the post How to Write to a File in Java examples are already given to write to a file in Java but the examples shown there would create a new file or overwrite existing file when writing. Sometimes you may need to append to an existing file rather than overwriting it so this post shows options to append content to a file in Java.

In Java there are two classes FileWriter and FileOutputStream for writing to a file. Where FileWriter is meant for writing streams of characters and FileOutputStream is used for writing streams of raw bytes. Both of these classes have a constructor with a boolean argument. When that boolean argument is passed as true then the content will be written to the end of the file.

For example– public FileWriter(File file, boolean append);

You should always use the wrapper classes BufferedWriter and BufferedOutputStream rather than using these classes directly.

Apart from these classes Files class added in Java 7 also provides methods for appending to a file in Java. There is Files.write() method which can be used.

Files.write(path, bytes, StandardOpenOption.APPEND);

Another method is-

Files.newBufferedWriter(Path path, StandardOpenOption.APPEND);

Java program to append to a file in Java

Let’s see examples of appending to a file in Java using the above mentioned options.

Appending to a file using Java BufferedWriter

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class AppendFile {

  public static void main(String[] args) {
    //Change path for windows
    appendToFile("D://test.txt");
  }

  private static void appendToFile(String fileName){
    BufferedWriter bw = null;
    try {
      // wrapping FileWriter instance, passing second arg 
      // as true for appending
      bw = new BufferedWriter(new FileWriter(fileName, true));
      bw.write("This is a test line");
      bw.newLine();
      bw.write("Line written by Java program in knpCode.com");
      bw.newLine();		
    }catch (IOException e) {
       e.printStackTrace();
    }finally{
      if(bw != null){
        try {
          bw.close();
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
      }
    }
  }
}

Appending to a file using Java BufferedOutputStream

If you have to write raw bytes then you can use BufferedOutputStream class. In the example code getBytes() method is used to encode string into bytes.

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class AppendFile {

  public static void main(String[] args) {
    //Change path for windows
    appendToFile("D://test.txt");
  }

  private static void appendToFile(String fileName){
    BufferedOutputStream bos = null;
    try {
      // wrapping FileOutputStream instance, passing second arg 
      // as true for appending
      bos = new BufferedOutputStream(new FileOutputStream(fileName, true));
      // \r\n for windows
      bos.write("This is a test line\r\n".getBytes());
      bos.write("Line written by Java program in knpCode.com\r\n".getBytes());
    }catch (IOException e) {
       e.printStackTrace();
    }finally{
      if(bos != null){
        try {
          bos.close();
          } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
      }
    }
  }
}

Java program to append 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 AppendFile {

  public static void main(String[] args) {
     String content = "This is a test line.\nLine written by Java program in knpCode.com.";
     try {
      Files.write(Paths.get("D:\\test.txt"), content.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Append to a file using Files.newBufferedWriter() method

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AppendFile {
  public static void main(String[] args) {
    String content = "This is a test line.\nLine written by Java program in knpCode.com.";		
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get("D:\\test.txt"), StandardOpenOption.APPEND)) {
       bw.write(content);			 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Here try-with-resources is used to close the resources automatically rather than closing them explicitly using finally block.

That's all for the topic How to Append to a File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment