×

Java InputStreamReader

What is InputStreamReader?

An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can be provided explicitly or by name, or the platform's default charset can be allowed. It comes under the java.io package and extends the abstract class Reader. InputStreamReader is often known as the path which connects streams and character streams as it reads a byte from the given input stream of character.

How to Create InputStreamReader?

Following are the steps to create an InputStreamReader.

Importing the java.io.InputStreamReader package is the first step in creating an InputStreamReader without this package, we cannot implement InputStreamReader. After we've imported the package, we must follow the steps below.

First, we create an InputStreamReader, which has a reference variable has st. Then we need to create a FileInputStream which has a reference variable fl. The following example demonstrates the above lines.

FileInputStream fl = new FileInputStream( path);
InputStreamReaderst   = new InputStreamReader( fl  );

2. The fetched data is stored using default character encoding by implementing this code. We can also define the character encoding as per the file or one's need. The character encoding can be either UTF8 or UTF16. We have specified the character encoding in the file in the following code by using the Charset class.

InputStreamReaderst   = new InputStreamReader( fl, Charset c );

Constructors of InputStreamReader

Following are the Constructors  provided by InputStreamReader:

  • InputStreamReader(InputStreamst): This constructor is implemented when there is a need to create an InputStreamReader that has the default charset.
  • InputStreamReader(InputStreamst, Charset ): This constructor is implemented when there is a need to create an InputStreamReader that has the specified charset.
  • InputStreamReader(InputStreamst, CharsetDecoder dc): This constructor is implemented when there is a need to create an InputStreamReader that has the specified charset decoder.
  • InputStreamReader(InputStreamst, String name): This constructor is implemented when there is a need to create an InputStreamReader that uses the named charset

Methods of InputStreamReader

Following are the methods provided by InputStreamReader.

  • ready()

This is a method with a return type. This method is implemented when there is a need to check whether the character stream is ready to perform its function ( i.e., whether it can read or not ).

An InputStreamReader is considered ready to perform its function, If an InputStreamReader's input buffer is empty or bytes are available to be read from the underlying byte stream.

  • read(char[] arr)

It is used when it is necessary to read characters from a reader and store them in a predefined array.

  • read(char[] arr, int st, int l)

It is used when several characters equal to length must be read from the reader and stored in the specified array starting at the beginning.

  • close( )

This method is implemented when there is a need to close cInputStreamReader and releases all the Streams attached to it.

 Once this method is implemented, the stream gets closed. Thus, methods such as ready( ), ready(), and other mentioned methods in the articles won't perform their function and will throw an IOException.

  • getEncoding() Method

This method is implemented when there is a need to acquire the type of encoding is implemented to save the fetched data in the input stream.

  • mark()

When it's necessary to mark the point in the stream where data has been read, this method is implemented

  • reset()

This is a method with a return type. It returns the control to the position where the mark was set in the stream.

import java.io.InputStreamReader;
import java.io.FileInputStream;
public class a {
public static void main(String[] args) {
char[] arr = new char[14];


        try {


            FileInputStream fl = new FileInputStream("d://sample.txt");




InputStreamReader File_input = new InputStreamReader(fl );




File_input.read(arr);
System.out.println("File contains the following data:");
System.out.println(arr);




input.close();
}


catch(Exception e) {
            e.getStackTrace();
}
    }
}

In the above code, first, we imported the important packages to implement FileInputStream and InputStreamReader.

Then we created an array of characters as reference variable as arr and size of 14 as it is the size of the data inside the file.

Then we created a FileOutputStream in which as reference variable as fl and contains specified file path as d://sample.txt. And created an InputStreamReader, a reference variable as File_input, and a default encoding.

Then we read the characters from the file stores them in an array of arrays. To see the data inside the file, we have to print the array. Following is the output obtained when the above code is implemented.

What is InputStreamReader?

The file contains the following text: Hello Everyone, and the same text is shown in the output.


Related Topics

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

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

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.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Trim Method in String 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...

3 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.