Site icon TechVidvan

Java FileReader Class with Examples

java filereader

Using Files or Blob objects to specify the file or data you want to read, the FileReader object allows Web applications to read the contents of files or raw data buffers stored by a user’s computer.

Here are some key points about FileReader in Java

try (FileReader reader = new FileReader("sample.txt")) {
    int character;
    while ((character = reader.read()) != -1) {
        System.out.print((char) character);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Benefits:

The FileReader property allows web applications, using Files or Blob Objects to specify a file or data that they will open in an asynchronous manner, to access contents of files and Raw Data buffers from the user’s computer.

Example

import java.io.*;
class TechVidvan{
  public static void main(String[] args)
  {
    try {
      FileReader fileReader= new FileReader("output.txt");

      System.out.println("Text in tutorial: \n");
      int i;
      while ((i = fileReader.read()) != -1) {
        System.out.print((char)i);
      }
    }

    catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output:
Text in tutorial:
welcome to TechVidvan Java Course

FileReader:

Java IO FileReader Class:

A Java FileReader class that can read a stream of characters out of files is available in the java.io package.

The Java IO FileReading class uses either the requested charset or the default keyboard format on your platform to read from bytes to characters.

First, here’s a Blob-like constructor

new File(fileParts, fileName, [options])

fileParts – is an array of Blob/BufferSource/String values.
fileName – file name string.
options – optional object:
lastModified – timestamp (integer) of the last modification.

Conclusion

Java.io.FileReader class provides a convenient way of reading characterally derived data from the file in Java. You can view the contents of a file’s characters by character when you create an object called FileReader and use your Read() method. Remember to handle potential exceptions by wrapping the code in a try-catch block and closing the file reader object after reading the file.

Exit mobile version