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 to append text to a pre-existing file without creating it once again.
This article will discuss 7 of those methods.
Method 1: Using FileWriter
java.io.FileWriter
has a write()
method which takes a string argument.
This string argument is the content to be written to the file.
FileWriter
has a constructor which takes 2 arguments:
First, file path and
Second, a boolean
value. If this value is true
, then the file is opened in append mode and if false
, then the file will be opened in write mode.
If the file is not opened in append mode then it will be overwritten. Example,
import java.io.FileWriter; import java.io.IOException; public class AppendFileWriterExample { public static void main(String[] a)() { 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 BufferedWriter
java.io.BufferedWriter
can also be used to append to file using the underlying FileWriter
object.
Create a FileWriter
in append mode as explained in the previous method and supply it to a BufferedWriter
object. Example,
import java.io.IOException; import java.io.FileWriter; import java.io.BufferedWriter; public class AppendBufferedWriterExample { public static void main(String[] a) { FileWriter writer = null; BufferedWriter bwr = null; try { File file = new File("append.txt"); // file writer in append mode writer = new FileWriter(file, true); bwr = new BufferedWriter(fr); bwr.write("appendedText"); } catch(IOException io) { ioe.printStackTrace(); } finally { if(writer != null) { writer.close(); } if(bwr != null) { bwr.close(); } } } }
Method 3: Using PrintWriter
java.io.PrintWriter
accepts an object of BufferedWriter
, which in turn is created using an object of FileWriter
as shown in the earlier example.
FileWriter is created in append mode and thus, PrintWriter
can be used to append to a file. Example,
import java.io.IOException; import java.io.PrintWriter; import java.io.FileWriter; import java.io.BufferedWriter; public class AppendBufferedWriterExample { public static void main(String[] a) { PrintWriter pwr = null; FileWriter writer = null; BufferedWriter bwr = null; try { File file = new File("append.txt"); // file writer in append mode writer = new FileWriter(file, true); bwr = new BufferedWriter(fr); pwr = new PrintWriter(bwr); pwr.println("appendedText"); } catch(IOException io) { ioe.printStackTrace(); } finally { if(writer != null) { writer.close(); } if(bwr != null) { bwr.close(); } if(pwr != null) { pwr.close(); } } } }
Method 4: Using Files class
java.nio.file.Files
class has a write()
method. This method takes 3 arguments: First, a java.nio.file.Path
object representing the path of file to be accessed,
Second, 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; public class FilesExample { public static void main(String[] a) { 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 5: 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, a java.io.File
object pointing to the file which needs to be written,
Second, the string that represents the content to be appended to the file, and
Third, 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; public class FilesExample { public static void main(String[] a) { 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.
Guava library can also be used to append to a file as shown in the code example below.
import java.io.File; import com.google.common.base.Charsets; import com.google.common.io.CharSink; import com.google.common.io.FileWriteMode; importcom.google.common.io.Files; public class GuavaExample { public static void main(String[] args) { CharSink charSink = Files.asCharSink(new File("f:\\testfile.txt"), Charsets.UTF_8, FileWriteMode.APPEND); try { charSink.write("appendedText"); } catch (IOException e) { e.printStackTrace(); } } }
Files class in Guava library has a static method asCharSink
which accepts three arguments:
First, a file object that points to the file to be appended,
Second, character set in which the text will be appended, and
Third, writing mode, which in this case will be append. This is specified as a java enum FileWriteMode
.
To add Guava library to your project, use the following dependency as per the build tool.
<!– Maven –>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
// Gradle
compile group: ‘com.google.guava’, name: ‘guava’, version: ‘23.0’
Method 6: 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 using any of the file writing methods in java.
Example,
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.FileNotFoundException; import java.io.IOException; public class AppendExampleOld { public static void main(String[] a) { appendToFile(); } 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(); } } } }
This 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.
Do not forget to click the clap if the article was useful.