In this tutorials we are going to see how to append content into existing file using FileWriter in Java.
The constructor FileWriter(file,true) is used to append content into existing file.By default FileWriter(file) will replace all existing content with new content.
1.Create project called JavaMisc.
2.Create package called com.javatutorialscorner.io
Create java class called FileWriter under com.javatutorialscorner.io package.
FileWriter.java
package com.javatutorialscorner.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileWriter {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedWriter bw = null;
java.io.FileWriter fw = null;
String message = "This is new String going to append in the File named JavaTutorialsCorner";
File file = null;
try {
file = new File("C:\\jtc\\javatutorialscorner.txt");
if (!file.exists()) {
file.createNewFile();
}
fw = new java.io.FileWriter(file.getAbsoluteFile(),true);
bw = new BufferedWriter(fw);
bw.write(message);
bw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The file already contains the following content.
Now run the program open the file at specified location, the new String append with existing String.
This is test String to be written in File named JavaTutorialsCorner.
This is test String to be written in File named JavaTutorialsCorner.This is new String going to append in the File named JavaTutorialsCorner
0 comments:
Post a Comment