We can use File Writer Object to write Character Data(text data) to the File.
Constructors :
FileWriter fw = new FileWriter(String fileName)
FileWriter fw = new FileWriter(File fileReference)
Above constructors will by default override the file name mentioned but to append the data to the file below constructors can be used.
FileWriter fw = new FileWriter(String fileName, boolean append)
FileWriter fw = new FileWriter(File fileReference, boolean append)
Note : If the file mentioned in the above constructors are not available then all FileWrite constructor will create the a new file to write into it.
Methods of FileWriter Class :
write(int ch); //to Write a single character into the file using its UNICODE
write(char[] ch);
write(String s);
flush(); //To save/write the data into the file we use flush method
close();
Example of FileWriter in java :
package com.fileDemo;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException {
File f = new File("/home/tyson/Desktop/temp/file1");
FileWriter fw = new FileWriter(f);
fw.write("Hello World \nThis is java example");
fw.flush();
fw.close();
}
}
Note : The problem with FileWriter is we have to insert line separator (\n) manually, which is varied from System to System. It is very difficult to the programmer. Hence the concept of BufferdWriter and PrintWriter came into picture