Home Tutorial Java Io Append a string to an existing file

 
 

Append a string to an existing file
Posted on: February 17, 2011 at 12:00 AM
In this section, you will learn how to append a string to existing file. This will be done using FileWriter() constructor method of FileWriter Class.

Append a string to an existing file

In this section, you will learn how to append a string to existing file. This will be done using FileWriter() constructor method of  FileWriter Class.

The syntax is given of FileWriter constructor :

public FileWriter(File file, boolean append) throws IOException

Description

This constructor takes the File name as object and produce a FileWriter object. If the boolean append is set to true then bytes will be written to the end of the file rather than the beginning.

Given below example will give you clear idea :

Example :

package roseindia;

import java.io.*;

public class AppendStringFile {

public static void main(String[] args) throws Exception {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(
"DemoFile.txt"));
out.write("This string is written first\n");
out.close();
out = new BufferedWriter(new FileWriter("DemoFile.txt", true));
out.write("This string is appended");
out.close();
BufferedReader in = new BufferedReader(new FileReader(
"DemoFile.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
System.out.println("exception occoured" + e);
}

}

}

Output

The message will appear in command prompt :

This string is written first                                                                                                                 
This string is appended

Download Source Code

Related Tags for Append a string to an existing file:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.