Advertisement



< Prev
Next >



InputStreamReader



InputStreamReader class is a subclass of Reader abstract class. Using any standard input stream, we can read the data in terms of bytes but what if we wanted to read data in terms of characters? That's when we are going to use InputStreamReader class.

InputStreamReader is wrapped around an input stream(that reads in bytes) to read data in the form of characters from it, hence InputStreamReader class acts as a converter of bytes to characters.




Constructor :


InputStreamReader(InputStream is)
This constructor creates an InputStreamReader object wrapped around an InputStream to read data from it in the form of characters.
Example-:
FileInputStream fis = new FileInputStream("D://TextBook.txt");
InputStreamReader isr = new InputStreamReader(fis);
In this example, we have wrapped an InputStream i.e. FileInputStream, inside InputStreamReader. FileInputStream class reads data out of a file TextBook.txt in the form of bytes and this data will be converted to characters, when it is read using InputStreamReader class.




Point to remember


FileInputStream is a subclass of InputStream




Methods for reading InputStreamReader


Some methods that we generally use while working with InputStreamReader are shown in the table below :

Methods Description
available()
This method gives the remaining number of bytes available to read from this character input stream's buffer.

read()
This method reads one character at a time from this character input stream's buffer.

read(char[])
This method reads a whole character array at a time from this character input stream's buffer.

close()
This method closes this input stream and also frees any resources connected with this character input stream.




Advertisement




Reading characters from a file using read() method of InputStreamReader.


We are reading an existing file called TextBook.txt using its path D:/TextBook.txt. Let's say the contents of this file are -
Hello there!
How are you doing?

// Program to create an input stream for reading the data and convert bytes to character while reading a byte 

//stream

import java.io.*;

class A
{
public static void main(String... ar)
{
try
{
FileInputStream fis= new FileInputStream("TextBook9.txt"); 
InputStreamReader isr= new InputStreamReader(fis); 
int c;

while( (c=isr.read())!=-1) 
{
System.out.print((char)c);
}
}
catch(IOException e)
{
System.out.println(e);
}

}
}



Output is -:


Hello there!
How are you doing? 


Program Analysis






Please share this article -




< Prev
Next >
< CharacterStream
OutputStreamWriter>



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement