InputStream vs InputStreamReader [英] InputStream vs InputStreamReader
问题描述
在 InputStreamReader
上使用 InputStream
有什么好处,反之亦然。
What's the benefit of using InputStream
over InputStreamReader
, or vice versa.
以下是 InputStream
的实例:
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
是祖先所有可能的 stream 字节的类,它本身没有用,但所有的子类(比如你使用的 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
),如果您需要使用文本,请使用输入StreamReader
..
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 vs InputStreamReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!