简体   繁体   中英

Is there ever a reason not to wrap InputStreamReader with BufferedReader?

I have the following code to read from a CSV:

InputStream inp = getClass().getResourceAsStream(filename);
InputStreamReader r = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(r);

On answered questions: Java BufferedReader , Convert InputStream to BufferedReader , What is the difference between Java's BufferedReader and InputStreamReader classes?

BufferedReader[BR] and InputStreamReader[ISR] both implement the same interfaces. BR has every method that ISR has with the additional methods including the ever so useful readLine() method and less useful but still relevant skip() method. You don't necessarily need BR to read single characters although BR can do the same more efficiently than ISR in this respect. The only significant difference is that FileReader is a subclass of ISR but not BR, although I have had sources on this website say that FileReader isn't really used anymore due to alternatives.

My research says that everything ISR can do is done better by BR. I am a young developer so every defined or imported class to me seems relevant. What I am trying to grasp is if some classes are no longer used, with new versions or frameworks replacing them. I want to know what more experienced developers have to say. SO, is there a reason to not use BR when using ISR?

QuickLinks to API:
BufferedReader
InputStreamReader


I see some confusion in your post about ISR and BR.

1) You are saying that

My research says that everything ISR can do is done better by BR

But lets look at JavaDoc for each of them:

ISR

public class InputStreamReader extends Reader

An InputStreamReader is a bridge from byte streams to character streams:

BR

Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

As you can see ISR converts bytes to chars. BR on other hand needs chars. Thats why BR needs to use ISR to read from InputStream .

2) As to the original question why not to just use ISR. You can definately do that, but in order to gain performance you want to use BR. You might ask why ISR was not implemented using buffering? Because ISR is designed to do one thing good and that is to read and convert bytes to chars. The buffering part is moved into the Decorator class that is BR. This is done in order to be able to add buffering capabilities to any Reader and not only ISR.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM