FileWriter

FileWriter class can be used for writing character data to the file.

  1. FileWriter fw = new FileWriter(String fname)
    FileWriter fw = new FileWriter(File file)
    The above 2 constructors creates a file object to write character data to the file.
  2. If the file already contains some data it will overwrite with the new data.Instead of overriding if you want perform append, then we have to use the below constructors.

    FileWriter fw = new FileWriter(String name, boolean append)
    FileWriter fw = new FileWriter(File f, boolean append)

  3. If the underlying physical file is not already available then these constructors will create the required file also.
Important methods of FileWriter Class
  1. void write(int ch) throws IOException
    for writing single character to the file.
  2. void write(String s)throws IOException.
  3. void write(char [] ch) throws IOException.
  4. void flush()
    To guaranteed that the last character of the data should be required to the file.

Example:

 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileDemo {
	public static void main(String[] args) throws IOException {
		File f = new File("java2learn.txt");
		System.out.println(f.exists());
		FileWriter fw = new FileWriter(f, true);
		System.out.println(f.exists());
		fw.write(97);
		fw.write("execute\nprogram\n");
		char[] ch1 = { 'a', 'b', 'c' };
		fw.write(ch1);
		fw.flush();
		fw.close();
	}
}

FileReader

FileReader class can be used for reading character data from the file.

Constructors

FileReader fr = new FileReader(String name);
FileReader fr = new FileReader(File f);

Important methods of FileReader Class
  1. int read():
    For reading next character from the file. If there is no next character this method returns -1.
  2. int read(char[] ch)
    To read data from the file into char array.
  3. void close()
    To close FileReader.

Example:

 
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileDemo {
	public static void main(String[] args) throws IOException {
		File file = new File("java2learn.txt");
		FileReader fr = new FileReader(file);
		System.out.println(fr.read());
		char[] ch2 = new char[(int) (file.length())];
		System.out.println(ch2.length);
		fr.read(ch2);
		for (char ch1 : ch2) {
			System.out.print(ch1);
		}
	}
}

The usage of FileReader and FileWriter is inefficient because,

  1. While writing the data by using FileWriter, We have to insert line separators manually,which is extra risk to the programmer.
  2. Reading and writing takes place character by character ,which increases the number of I/O operations and effects performance of the system.

To overcome these problems sun people has introduced BufferedReader and BufferedWriter classes.