有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中InputStream和InputStreamReader的区别

我读到InputStream用于基于字节的读取,它一次读取1个字节。 InputStreamReader用于基于字符的读取,因此它一次读取一个字符,因此无需先将其转换为int,然后再读取

这里是使用InputStream进行读取

 InputStream input=new FileInputStream("D:/input.txt");

 int c;

 while((c=input.read())!=-1)
 {
    System.out.print((char)c);
 }

下面是使用InputStreamReader进行的阅读

InputStream input=new FileInputStream("D:/input.txt");

reader=new InputStreamReader(input,"UTF-8");

int c;

while((c=reader.read())!=-1)
{
    System.out.print((char)c);
}

{}和{}之间有什么区别?在这两种情况下,我都必须使用一个int,然后读取它,最后如果我想打印数据,我必须用“(char)c”转换它

那么使用InputStreamReader有什么好处呢


共 (4) 个答案

  1. # 1 楼答案

    InputStream通常总是连接到某些数据源,如文件、网络连接、管道等。Java IO概述文本中也对这一点进行了更详细的解释

    InputStreamReader获取inputstream,并在读取时将字节Strem转换为字符。例如,一些UTF字符是2字节,对输入流读取器的调用将读取这两个字节并自动将其转换为字符。它用于读取文本流

  2. # 2 楼答案

    有些编码包含跨越多个字节的字符。通过使用InputStream读取,您正在愚蠢地读取下一个字节,而不是InputStreamReader,后者可能会根据需要提前读取,以便为您提供下一个字符,而不是字节。换句话说,假设流中的下两个字节是0x00 0xA7。InputStream将在第一次读取时提供0x0,然后在下一次读取时提供0xA7。具有unicode编码的InputStreamReader在第一次读取时将返回0x00A7,即字符§

    请注意,在大多数情况下,最好使用BufferedReader包装InputStreamReader

  3. # 3 楼答案

    对于InputStreamReader,可以使用“char c”代替“int c”,也可以使用“null”代替“-1”值。像这样:

    InputStream input=new FileInputStream("D:/input.txt");
    
    reader=new InputStreamReader(input,"UTF-8");
    
    char c;
    
    while((c=reader.read())!=null)
    {
    System.out.print(c);
    }
    

    因为您使用的是InputStreamReader,它可以进行基于字符的读取。 因此,不需要设置数据类型“int”,然后使用“char”强制转换它,这是不必要的。 我们需要在InputStream的情况下这样做,就像它进行基于字节的读取一样

  4. # 4 楼答案

    什么是InputStreamInputStreamReader之间有很大的区别。一个读取字节,而另一个读取字符。根据使用的编码,一个字符可能超过1字节

    ^{}

    Reads the next byte of data from the input stream

    ^{}

    Reads a single character.

    InputStreamReader充当Java中读取数据的两种方式之间的桥梁:一种将字节流桥接到字符流的方式From its Javadoc

    An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.

    Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.