×

Java file Reader

File Reader:

It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file.

Input Stream:

Java.io package contains the Input Stream class. This stream represents the set of bytes, It is an abstract class.

Abstract Class:

 Abstract methods are present in this class. An abstract method has an abstract keyword, and these methods don’t have anybody.

The syntax for object creation In Input Stream:

InputStream object1 = new FileInputStream();

Note: To create an object, we use FileInputStream because InputStream is an abstract class.

File Reader class Extends Reader class.

Reader Class:

It is used to read characters from the input stream, It throws an IO Exception while reading the input.

Sub-Classes in Reader:

  • Buffered Reader
  • Input Stream Reader
  • File Reader
  • String Reader.

Constructors In File Reader Class:

  • FileReader (File f)
  • FileReader (FileDescripter fdes)
  • FileReader (String fN)

FileReader (File f):

It creates or generates a File Reader object to read the characters or data from the file.

Syntax for Object Creation:

FileReader obj1 = new FileReader(File f);

FileReader (FileDescripter fdes):

It creates or generates a File Reader object to read data, it Provides a File descriptor to read data.

Syntax for Object Creation:

FileReader obj1 = new FileReader(FileDescripter fdes);

FileReader (String fN):

It creates or generates a File Reader object to read data, it Provides a file name to read data from the file.

Syntax for Object Creation:

FileReader obj1 = new FileReader(String fN);

Methods in FileReader Class:

  • read ()
  • read (char c[])
  • read (char c[], int start , int length)
  • close ()
  • skip (long n)

read():

It is used to read single characters from the stream. It returns -1 if it reaches the end of the input. It represents whether the next character is present or not. The return type of the read() method is int(Integer). It throws IOException i.e, Input or Output exception when an error occurs with inputs and outputs.

Syntax:

public int read() throws IOException

Program:

import java.io.*;  
class FileReaderExample {  
public static void main(String args[])throws Exception{ 
       FileReader f=new FileReader("cse.txt");    
        int i;
        while((i=f.read())!=-1)
   { 
System.out.print((char)i); 
}    
         f.close();    
  }    
}    

Output:

javatpoint

Note:  Here, In cse.txt file contains data as JavaTpoint then, by using the read() method we also get output as JavaTpoint.

read (char c[]):

It reads the characters in the form of an array, It has a return value, An IO Exception occurs when an input or output error occurs.

Syntax:

public int read( char c[]) throws IOException

Program:

import java.io.*;  
class FileReaderExample {  
public static void main(String args[])throws Exception{ 
try
{
       FileReader f=new FileReader("cse-c.txt");    
       char c[] = new char[5];
     f.read(c);         
 System.out.println(Arrays.toString(c);    
         f.close();    
  }  
Catch (Exception e)
{
System.out.println(e);  
}
}

OUTPUT:

 [‘W’,’ E’,’ L’,’ C’,’ O’]

NOTE: Here, In cse-c. txt file contains WELCOME as data then it reads the data in the form of arrays and it gives output as above.   

read (char c[], int start , int length):

 It stores the reading characters in the array form, It returns the count of characters. An integer is the return type.

Syntax:

public int read(char[] c, int start, int length)
  • c -It is the Destination buffer
  • start – at which index it starts writing characters.
  • length -.Several characters

Program:

import java.io.*;
 class Example3{
   public static void main(String[] s) throws IOException{


            FileReader object2 = new FileReader(“Vishu.txt”);
     char c[]=new char[10];


        object2.read(c,0,4);
        System . out .  println(c);
   object2.close();
}
catch (IOException E){
System. out. println(E);
}

OUTPUT:

JAVA

NOTE: Here, In Vishu. txt file contains the data Java Programming hence by using the above method we get output as JAVA.    

 It is used to close the character stream. The return type of the close() method is void. If the stream has been closed, performing methods like read() and other methods throw an IOException.

SYNTAX:

public void close()

Program:

import java.io.*;
 class Example3{
   public static void main(String[] s) throws IOException{


            FileReader object2 = new FileReader(“Vishu.txt”);
     char c[]=new char[10];
        object2.read(c,0,4);
        System . out .  println(c);
   object2.close();
}
catch (IOException E){
System. out. println(E);
}

OUTPUT:

JAVA

NOTE: Here, In Vishu. txt file contains the data Java Programming hence by using the above method we get output as JAVA.

skip (long s):

It returns the number of skipped characters from the stream. Long is the return type.

Syntax:

public long skip(long s)

Program:

import java.io.*;
class Example14
{
  public static void main(String s[]) throws IOException
 {
  FileReader b = new FileReader (Vishu.txt);
  System . out . print((char)b.read());
b.skip(3);
  System . out . print((char)b.read());


   }  
}

OUTPUT:

W
O

Related Topics

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.