Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between InputStream and InputStreamReader in java

Tags:

java

I read that InputStream is used for byte based reading it reads 1 byte at a time. And InputStreamReader is used for character based reading so it reads one character at a time so no need to convert this first to int then read it.

Here is reading using InputStream.

 InputStream input=new FileInputStream("D:/input.txt");

 int c;

 while((c=input.read())!=-1)
 {
    System.out.print((char)c);
 }

here is reading using InputStreamReader

InputStream input=new FileInputStream("D:/input.txt");

reader=new InputStreamReader(input,"UTF-8");

int c;

while((c=reader.read())!=-1)
{
    System.out.print((char)c);
}

What is difference between InputStream and InputStreamReader? In both case I have to use a int and then read it and at the end if I want to print that data I have to cast that with "(char)c".

So what is advantage of using InputStreamReader?

like image 311
user3387084 Avatar asked Jan 06 '23 17:01

user3387084


1 Answers

There's a big difference between what is an InputStream and an InputStreamReader. One reads bytes whereas the other one reads character. Depending on the encoding used, one character may be more than 1 byte.

From InputStream.read():

Reads the next byte of data from the input stream

From InputStreamReader.read():

Reads a single character.

InputStreamReader serves as a bridge between those two ways of reading data in Java: a way of bridging byte streams to character streams. From its Javadoc:

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.

like image 95
Tunaki Avatar answered Jan 30 '23 22:01

Tunaki