问题
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