java reader vs. stream

心已入冬 提交于 2019-12-31 00:46:12

问题


I was reading about Java I/O and found some interesting areas like streams, readers etc.

 InputStream input = new FileInputStream("input-file.txt");
 int data = input.read();
 while(data != -1){
   data = input.read();
 }

I can do the same thing by using Readers as follows:

Reader reader = new FileReader("input-file.txt");
 int data = reader.read();
 while(data != -1){
     char dataChar = (char) data;
     data = reader.read();
 }

As I know, Streams are used to retrieve input from continuously flowing data.

Now I am confused with the difference between Streams & readers; and if we wraps the stream with a buffered reader - how it break lines, since stream is a continuously flowing thing.

I found some reference sites like this site. But I can't understand the difference.

Please can someone please help me to understand?


回答1:


Readers are to read text data with particular character encoding (UTF-8, ISO etc..)

while on the other hand, streams are binary data.

They work same but there parent classes are different.

in a nutshell, if you have to read binary data and save it somewhere, use stream.

If you have to read text in a particular encoding and then play with it, then use readers.

Hope this answers.



来源:https://stackoverflow.com/questions/23799015/java-reader-vs-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!