Append A File in Java 6 - Java
Home » Java

Append A File in Java 6

24 November 2009 No Comment

In this article we append to a text file using Java 6. Again we go to java.io package. Following points you need to consider while doing this.

  • Close the file in finally block. You can set the BufferWriter to null also.
  • FileWriter constructor has two input values. First is the file, and second whether to create new file each time. If you give ‘true’ as input, then the file will not be created instead appended.
  • Handle exception appropriately.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class AppendToAFile {

	public static void main(String[] args) {
		AppendToAFile appendToAFile = new AppendToAFile();
		appendToAFile.writeToAFile();

	}
	public void writeToAFile(){
		BufferedWriter buffWriter = null;
		try{
			buffWriter = new BufferedWriter (new FileWriter("C:\\SampleFile.txt",true));
			buffWriter.append("Appended This New Line");
			System.out.println("Append Successful");
		}catch(IOException ioe){
			ioe.printStackTrace();
		}finally{
			try{
				buffWriter.close();
			}catch(IOException ioe1){
				//Leave It
			}
		}
	}

}

 

More Related Posts in Java

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.