FileWriter Class

Character Encoding
This Class assumes that you want to decode the bytes in the file using the default character encoding for the program is running on. This may not always be what you want, and you cannot change it. So, if you want to specify a different character decoding scheme, try to avoid this class. OutputStreamWriter is the better option. The OutputStreamWriter lets you specify the character encoding scheme to use when writing bytes to the underlying file. Example
import java.util.*;
import java.io.*;
public class TestClass{
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("D:\\test.txt");
fw.write("Line No. 1");
fw.write("Line No. 2");
fw.write("Line No. 3");
fw.write("Line No. 4");
fw.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
Java FileWriter with append mode
When you create file using Java FileWriter Class you can decide whether you want to overwrite existing file with the same name or if you want to append to any existing file. You decide that by choosing what FileWriter constructor you use. When pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter(file);
In the above code, all existing content will be overridden.
FileWriter fw = new FileWriter(file,true);
Above code keep the existing content and append the new content to the end of a file.
Example
import java.util.*;
import java.io.*;
public class TestClass{
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("D:\\test.txt",true);
fw.write("Line No. 5");
fw.write("Line No. 6");
fw.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
Related Topics