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
}
}
}
}









Leave your response!