Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do an InputStream, InputStreamReader and BufferedReader work together in Java?

I am studying Android development (I'm a beginner in programming in general) and learning about HTTP networking and saw this code in the lesson:

private String readFromStream(InputStream inputStream) throws IOException {
  StringBuilder output = new StringBuilder();
  if (inputStream != null) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
    BufferedReader reader = new BufferedReader(inputStreamReader);
    String line = reader.readLine();
    while (line != null) {
      output.append(line);
      line = reader.readLine();
    }
  }
  return output.toString();
}

I don't understand exactly what InputStream, InputStreamReader and BufferedReader do. All of them have a read() method and also readLine() in the case of the BufferedReader.Why can't I only use the InputStream or only add the InputStreamReader? Why do I need to add the BufferedReader? I know it has to do with efficiency but I don't understand how.

I've been researching and the documentation for the BufferedReader tries to explain this but I still don't get who is doing what:

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

BufferedReader in = new BufferedReader(new FileReader("foo.in")); will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

So, I understand that the InputStream can only read one byte, the InputStreamReader a single character, and the BufferedReader a whole line and that it also does something about efficiency which is what I don't get. I would like to have a better understanding of who is doing what, so as to understand why I need all three of them and what the difference would be without one of them.

I've researched a lot here and elsewhere on the web and don't seem to find any explanation about this that I can understand, almost all tutorials just repeat the documentation info. Here are some related questions that maybe begin to explain this but don't go deeper and solve my confusion: Q1, Q2, Q3, Q4. I think it may have to do with this last question's explanation about system calls and returning. But I would like to understand what is meant by all this.

Could it be that the BufferedReader's readLine() calls the InputStreamReader's read() method which in turn calls the InputStream's read() method? And the InputStream returns bytes converted to int, returning a single byte at a time, the InputStreamReader reads enough of these to make a single character and converts it to int and returns a single character at a time, and the BufferedReader reads enough of these characters represented as integers to make up a whole line? And returns the whole line as a String, returning only once instead of several times? I don't know, I'm just trying to get how things work.

Lots of thanks in advance!

like image 673
schv09 Avatar asked Mar 31 '17 18:03

schv09


People also ask

What is InputStreamReader and BufferedReader?

BufferedReader reads a couple of characters from the specified stream and stores it in a buffer. This makes input faster. InputStreamReader reads only one character from specified stream and remaining characters still remain in the stream.

How does InputStreamReader work in java?

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.

What is the difference between InputStream and BufferedInputStream?

DataInputStream is a kind of InputStream to read data directly as primitive data types. BufferedInputStream is a kind of inputStream that reads data from a stream and uses a buffer to optimize speed access to data. data is basicaly read ahead of time and this reduces disk or network access.


3 Answers

This Streams in Java concepts and usage link, give a very nice explanations.

This

Streams, Readers, Writers, BufferedReader, BufferedWriter – these are the terminologies you will deal with in Java. There are the classes provided in Java to operate with input and output. It is really worth to know how these are related and how it is used. This post will explore the Streams in Java and other related classes in detail. So let us start:

Let us define each of these in high level then dig deeper.

Streams
Used to deal with byte level data

Reader/Writer
Used to deal with character level. It supports various character encoding also.

BufferedReader/BufferedWriter
To increase performance. Data to be read will be buffered in to memory for quick access.

While these are for taking input, just the corresponding classes exists for output as well. For example, if there is an InputStream that is meant to read stream of byte, and OutputStream will help in writing stream of bytes.

InputStreams
There are many types of InputStreams java provides. Each connect to distinct data sources such as byte array, File etc.

For example FileInputStream connects to a file data source and could be used to read bytes from a File. While ByteArrayInputStream could be used to treat byte array as input stream.

OutputStream
This helps in writing bytes to a data source. For almost every InputStream there is a corresponding OutputStream, wherever it makes sense.


UPDATE

What is Buffered Stream?

Here I'm quoting from Buffered Streams, Java documentation (With a technical explanation):

Buffered Streams

Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

Sometimes I'm losing my hair reading a technical documentation. So, here I quote the more humane explanation from https://yfain.github.io/Java4Kids/:

In general, disk access is much slower than the processing performed in memory; that’s why it’s not a good idea to access the disk a thousand times to read a file of 1,000 bytes. To minimize the number of times the disk is accessed, Java provides buffers, which serve as reservoirs of data.

enter image description here

In reading File with FileInputStream then BufferedInputStream, the class BufferedInputStream works as a middleman between FileInputStream and the file itself. It reads a big chunk of bytes from a file into memory (a buffer) in one shot, and the FileInputStream object then reads single bytes from there, which are fast memory-to-memory operations. BufferedOutputStream works similarly with the class FileOutputStream.

The main idea here is to minimize disk access. Buffered streams are not changing the type of the original streams — they just make reading more efficient. A program performs stream chaining (or stream piping) to connect streams, just as pipes are connected in plumbing.

like image 114
ישו אוהב אותך Avatar answered Oct 20 '22 21:10

ישו אוהב אותך


  • InputStream, OutputStream, byte[], ByteBuffer are for binary data.
  • Reader, Writer, String, char are for text, internally Unicode, so that all scripts in the world may be combined (say Greek and Arabic).

  • InputStreamReader and OutputStreamWriter form a bridge between both. If you have some InputStream and know that its bytes is actually text in some encoding, Charset, then you can wrap the InputStream:

    try (InputStreamReader reader =
            new InputStreamReader(stream, StandardCharsets.UTF_8)) {
         ... read text ...
    }
    

There is a constructor without Charset, but that is not portable, as it uses the default platform encoding.

On Android StandardCharset may not exist, use "UTF-8".

The derived classes FileInputStream and BufferedReader add something to the parent InputStream resp. Reader.

A FileInputStream is for input from a File, and BufferedReader uses a memory buffer, so the actual physical reading does not does not read character wise (inefficient). With new BufferedReader(otherReader) you add buffering to your original reader.

All this understood, there is the utility class Files with methods like newBufferedReader(Path, Charset) which add additional brevity.

like image 35
Joop Eggen Avatar answered Oct 20 '22 22:10

Joop Eggen


I have read lots of articles on this very topic. I hope this might help you in some way.

Basically, the BufferedReader maintains an internal buffer.

During its read operation, it reads bytes from the files in bulk and stores that bytes in its internal buffer.

Now byte is passed to the program from that internal buffer for each read operation.

This reduces the number of communication between the program and the file or disks. Hence more efficient.

like image 25
Iamsudip Avatar answered Oct 20 '22 21:10

Iamsudip