×

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

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 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.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.