×

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

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.