Skip to content

FileReader

  • to read characters data or text data.
  • Here, we can read character by character by character; not line by line.

Constructors

  1. FileReader fr = new FileReader(String fileName);
  2. FileReader fr = new FileReader(File f);

If no file is available, this will throw exception.

Methods

  1. int read ()
  2. Unicode value of character.
  3. int read (char[] ch)
  4. no of characters copied from file into array.
  5. void close()

Examples

Text File

Hello my name is Arjun.

Read File By Looping

  • Demo of a FileReader class.
    import java.io.FileReader;
    import java.io.IOException;
    
    
    class FileReaderDemo{
    
        // Method : int read()
        public static void main(String[] args){
            try{
                FileReader fr  = new FileReader("myText.txt");
                int i = fr.read();
                while(i != -1){ // Denotes no character
                    System.out.print((char)i); // Type-hinting
                    i = fr.read();
                }
                fr.close();
            }catch(IOException error){
                error.printStackTrace();
            }
        }   
    }
    

Read File With Character Array

  • Demo of a FileReader class using a array.
    import java.io.*;
    
    class FileReaderDemo{
        public static void main(String[] args){
            try{
                // Method : int read(char[] ch)
                File f = new File("myText.txt");
                // Dynamically allocating the size of the array according to the text length inside file.
                char[] ch = new char[(int)f.length()];
                FileReader fr = new FileReader(f);
                fr.read(ch);
                // Assigns each character into another character variable.
                for(char ch1:ch){
                    System.out.print(ch1);
                }
                fr.close();
            }catch(IOException error){
                error.printStackTrace();
            }
        }
    }