Easy Tutorial
❮ Net Multisoc Java String ❯

Java FileReader Class

Java Streams


The FileReader class extends the InputStreamReader class. This class reads data from a stream in character format. You can create the required object using one of the following constructors.

Creates a new FileReader, given the File to read from.

FileReader(File file)

Creates a new FileReader, given the FileDescriptor to read from.

FileReader(FileDescriptor fd)

Creates a new FileReader, given the file name to read from.

FileReader(String fileName)

After successfully creating the FileReader object, you can manipulate the file using the methods listed below.

Number Description
1 public int read() throws IOException <br> Reads a single character, returning an int representing the character read.
2 public int read(char [] c, int offset, int len) <br> Reads characters into an array, returning the number of characters read.

Example

import java.io.*;

public class FileRead {
    public static void main(String args[]) throws IOException {
        File file = new File("Hello1.txt");
        // Create the file
        file.createNewFile();
        // Creates a FileWriter Object
        FileWriter writer = new FileWriter(file);
        // Write content to the file
        writer.write("This\n is\n an\n example\n");
        writer.flush();
        writer.close();
        // Create FileReader object
        FileReader fr = new FileReader(file);
        char[] a = new char[50];
        fr.read(a); // Read content into array
        for (char c : a)
            System.out.print(c); // Print each character
        fr.close();
    }
}

The above example compiles and runs with the following output:

This
is
an
example

Java Streams

❮ Net Multisoc Java String ❯