FileWriter
Constructors
FileWriter fw = new FileWriter(String name);
FileWriter fw = new FileWriter(File f);
FileWriter fw = new FileWriter(String name, boolean append);
FileWriter fw = new FileWriter(File f, boolean append);
Constructors listed 1 and 2 overrides the existing data, but Constructors listed 3 and 4 appends to existing data.
If no file is available, this will create that file.
Methods
write (int ch)
-
to write a single character to the file.
fw.write(100); // Unicode value for d is 100 fw.write('d'); // Both writes d.
-
write(char[] ch)
write(String s)
flush()
- To guarantee our data including last char also on written property.
close()
Examples
FileWriter Demo
import java.io.*;
class FileWriterDemo {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("abc.txt");
fw.write(100);
fw.write("abc \n Software");
// Paragraph Break
fw.write('\n');
// Character Array
char[] ch = { 'a', 'b', 'c' };
// Writing character array
fw.write(ch);
fw.write('\n');
fw.flush();
fw.close();
} catch (IOException error) {
error.printStackTrace();
}
}
}
FileWriter Append Demo
import java.io.*;
class FileWriterAppendDemo{
public static void main(String[] args){
try{
// Appends
FileWriter fw = new FileWriter("abc.txt",true);
fw.write("\n Arjun");
fw.flush();
fw.close();
}catch(IOException error ){
error.printStackTrace();
}
}
}