Menu
Topics Index
...
`


Input/Output: Exploring java.io > Character Streams >
Siva Nookala - 14 Apr 2016
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a Java FileInputStream.

FileReader Constructors:
ConstructorDescription
FileReader(File file)Creates a new FileReader, given the File to read from.
FileReader(FileDescriptor fd)Creates a new FileReader, given the FileDescriptor to read from.
FileReader(String fileName)Creates a new FileReader, given the name of the file to read from.

Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files.

FileReader Methods:
MethodDescription
int read() throws IOExceptionReads a single character. Returns an int, which represents the character read.
int read(char [] c, int offset, int len)Reads characters into an array. Returns the number of characters read.

Example Program:
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReaderWriter{

    public static void main(String args[]) throws IOException{

        File file = new File("Output.txt"); //LINE A

        // creates the file
        file.createNewFile();

        // creates a FileWriter Object
        FileWriter fw = new FileWriter(file);

        // writes the content to the file
        fw.write("This\nis\nJava\nMerit\nCampus."); // LINE B
        fw.flush();
        fw.close();

        // creates a FileReader Object
        FileReader fr = new FileReader(file);
        char [] output = new char[50];

        fr.read(output); // reads the content to the array

        for(char out : output)
        {
            System.out.print(out); // prints the characters one by one
        }

        fr.close();
    }
}

Output:
This
is
Java
Merit
Campus.

Description:
A text file Output.txt is taken and created. Input is taken into the FileWriter and is written onto the file. The file is read using FileReader and printed.

Things to try:
  • Try giving other inputs to File in LINE A.
  • Try giving other inputs to FileWriter in LINE B like "Your Online Java School"<cw>, "Don't just learn Java, do Java".

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.