How to append text to an existing file in java / Various methods of appending text to a file in java

Many times it happens that a file already exists with some contents and you need to add(or append) some text to it. Fortunately java provides many methods using which text can be appended to a pre-existing file without creating it once again. This post will discuss all of these methods.


Method 1: Using FileWriter
java.io.FileWriter provides a write method which takes a string argument which represents the content to be written to the file. It has a constructor which takes 2 arguments: first is the file path and second a boolean value. If this value is true, then the file is opened in append mode. If this argument is false, then the file will be opened in write mode. If the file is not opened in append mode then it will be overwrittenExample,

import java.io.FileWriter;
import java.io.IOException;
 
void appendToFile() {
   FileWriter writer = null;
   try {
        // open file in append mode
	writer = new FileWriter("f:\\testfile.txt", true);
	writer.write("appendedText");
   } catch (IOException e) {
	e.printStackTrace();
   } finally {
	if (writer != null) {
	   writer.close();
	}
   }
}

Method 2: Using Files class
java.nio.file.Files class has a write method. This method takes 3 arguments. First is a java.nio.file.Path object representing the path of file to be accessed, second is a byte array consisting of the contents to be written and third an object of type java.nio.file.OpenOption which represents the mode in which the file will be opened. Example,

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.io.IOException;
 
void appendToFile() {
   try {
	Files.write(Paths.get("f:\\testfile.txt"), "appendedText".getBytes(), 
                      StandardOpenOption.APPEND);
   } catch (IOException e) {
	e.printStackTrace();
   }
}

java.nio.file.StandardOpenOption is an enum that implements java.nio.file.OpenOption with values such as READ, WRITE, APPEND etc. These values represent the mode in which the file will be opened.
Note that all the classes used in the above example were added in Java 7. So if you are using java version below 7, then this method won’t work for you.


Method 3: Using FileUtils from Apache Commons
Apache Commons library has a org.apache.commons.io.FileUtils class. This class has writeStringToFile method which accepts 3 arguments: first is a java.io.File object pointing to the file which needs to be written, second is the string that represents the content to be appended to the file and the third is a boolean value. A true value means that the file will be opened in append mode and false means the file will be in write mode. If the file is not opened in append mode then it will be overwritten. Example,

import org.apache.commons.io.FileUtils;
import java.io.IOException;
 
void appendToFile() {
   try {
	FileUtils.writeStringToFile(new File("f:\\testfile.txt"), "appendedText", true);
   } catch (IOException e) {
	e.printStackTrace();
   }
}

For this method to work, you need to add Apache Commons Library to your application classpath.

Method 4: Reading file contents
This is a traditional method of appending text to a file in which the entire contents of the file are first read into a buffer and text to be appended is added to this buffer. Finally this buffer it written to the same file.

For different methods on reading and writing file refer this and this page respectively.

Example,

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
 
void appendToFile() {
   BufferedReader reader = null;
   // initialize a string buffer to hold file contents
   StringBuffer contents = new StringBuffer();
   try {
	// initialize file reader
	reader = new BufferedReader(new FileReader("f:\\testfile.txt"));
	String line = null;
	// read file line by line
	while ((line = reader.readLine()) != null) {
		// add current line to buffer
		contents.append(line).append("\n");
	}
   } catch (FileNotFoundException e) {
        e.printStackTrace();
   } catch (IOException e) {
	e.printStackTrace();
   } finally {
	if (reader != null) {
	   // close reader
	   reader.close();
	}
   }
 
   FileWriter writer = null;
   try {
        // append text to file contents
	contents.append("appendedText");
	// initialize file writer
	writer = new FileWriter("f:\\testfile.txt");
	// writer contents to file
	writer.write(contents.toString());
   } catch (FileNotFoundException e) {
	e.printStackTrace();
   } catch (IOException e) {
	e.printStackTrace();
   } finally {
	// close writer
	if (writer != null) {
	   writer.close();
	}
   }
}

Above method first reads the file line by line into a java.lang.StringBuffer. When all the contents are read, the text to be appended to the file is added to this buffer. This buffer is then written to the file using java.io.FileWriter.

This method is not an optimized way of appending text to a file since it reads the entire file first and thus involves more IO operations as compared to other methods. Also, the total lines of code in this method are also greater as compared to other methods.

Keep visiting!!!

Mark Your Impression

Close Menu