×

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

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 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 String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.