Home Tutorial Java Io Append a string to an existing file

 
 

Share on Google+Share on Google+
Append a string to an existing file
Posted on: February 17, 2011 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Append a string to an existing file:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 17, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com