【问题标题】:Character missing when use the InputStreamReader class in Java在 Java 中使用 InputStreamReader 类时缺少字符
【发布时间】:2020-07-15 05:40:27
【问题描述】:

我写了一些代码来逐个字符地读取文本文件,然后将其打印到屏幕上,但结果让我感到困惑,这里是:

这是我写的代码

import java.io.*;
import java.nio.charset.StandardCharsets;
public class learnIO
{


        public static void main(String[] args) throws IOException{

                var in = new InputStreamReader(new FileInputStream("test1.txt"), StandardCharsets.UTF_8);
                while(in.read() != -1){

                        System.out.println((char)in.read());
                }


        }


}

文件的内容和编码方案:

文件 test1.txt

test1.txt:ASCII 文本

猫 test1.txt

你好,世界!

结果是:

e

l

,

w

r

d

有些char漏掉了,为什么会这样?

【问题讨论】:

  • 你做了一会儿(in.read() != -1)。这会读取并丢弃一个字符。我也会使用 BufferedReader 而不是 InputStreamReader。

标签: java string input io stream


【解决方案1】:

InputStreamReader 的读取方法的返回类型为 int,占用 4 个字节 char 类型是 2 个字节,所以将 int 转换为 char 你跳过 2 个字节

参考https://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html

【讨论】:

    【解决方案2】:

    您需要在 BufferedReader 中使用 InputStreamReader,正如官方 oracle 文档中所说的那样

    InputStreamReader 是从字节流到字符流的桥梁:它读取字节并使用指定的字符集将它们解码为字符。它使用的字符集可以通过名称指定或明确给出,或者可以接受平台的默认字符集。

    每次调用 InputStreamReader 的 read() 方法之一都可能导致从底层字节输入流中读取一个或多个字节。

    为了实现字节到字符的高效转换,可能会从底层流中提前读取比满足当前读取操作所需的更多的字节。

    为了获得最高效率,请考虑将 InputStreamReader 包装在 BufferedReader 中。例如:

    BufferedReader 中 = new BufferedReader(new InputStreamReader(System.in));

    所以你的问题可以用下面的代码解决

     try {
                    // Open the file that is the first
                    // command line parameter
                    FileInputStream fstream = new FileInputStream("hello.txt");
                    // Get the object of DataInputStream
                    DataInputStream in = new DataInputStream(fstream);
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    //Read File Line By Line
                    char c;
                    while ((c = (char) br.read()) != (char) -1) {
                        // Print the content on the console
                        String character = Character.toString(c);
                        System.out.println(character);
                    }
                    //Close the input stream
                    in.close();
                } catch (Exception e) {//Catch exception if any
                    System.err.println("Error: " + e.getMessage());
                }
    

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2016-06-18
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多