InputStream 与 InputStreamReader [英] InputStream vs InputStreamReader
问题描述
使用 InputStream
而不是 InputStreamReader
有什么好处,反之亦然.
What's the benefit of using InputStream
over InputStreamReader
, or vice versa.
下面是一个 InputStream
的例子:
Here is an example of InputStream
in action:
InputStream input = new FileInputStream("c:\data\input-text.txt");
int data = input.read();
while(data != -1) {
//do something with data...
doSomethingWithData(data);
data = input.read();
}
input.close();
这是一个使用 InputStreamReader 的例子(显然是在 InputStream 的帮助下):
And here is an example of using InputStreamReader (obviously with the help of InputStream):
InputStream inputStream = new FileInputStream("c:\data\input.txt");
Reader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1){
char theChar = (char) data;
data = reader.read();
}
reader.close();
Reader 是否以特殊方式处理数据?
Does the Reader process the data in a special way?
只是想了解 Java 中的整个 i/o
流数据方面.
Just trying to get my head around the whole i/o
streaming data aspect in Java.
推荐答案
它们代表的东西有些不同.
They represent somewhat different things.
InputStream
是所有可能的 streams 字节的祖先类,它本身没有用,但它的所有子类(如 FileInputStream
> 您正在使用的)非常适合处理二进制数据.
The InputStream
is the ancestor class of all possible streams of bytes, it is not useful by itself but all the subclasses (like the FileInputStream
that you are using) are great to deal with binary data.
另一方面,InputStreamReader
(及其父Reader
)专门用于处理字符(所以是字符串),以便它们处理字符集编码(utf8、iso-8859-1,等等)优雅地.
On the other hand, the InputStreamReader
(and its father Reader
) are used specifically to deal with characters (so strings) so they handle charset encodings (utf8, iso-8859-1, and so on) gracefully.
简单的答案是:如果您需要二进制数据,您可以使用 InputStream
(也是一个特定的,如 DataInputStream
),如果您需要使用文本一个 InputStreamReader
..
The simple answer is: if you need binary data you can use an InputStream
(also a specific one like a DataInputStream
), if you need to work with text use an InputStreamReader
..
这篇关于InputStream 与 InputStreamReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!