×

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 Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.