【问题标题】:Java BufferedReader reads an empty txt file but doesn't return null [duplicate]Java BufferedReader 读取一个空的 txt 文件但不返回 null [重复]
【发布时间】:2020-03-03 11:07:15
【问题描述】:

我尝试使用 Java BufferedReader 读取一个空的 txt 文件。

这是我的代码:

    File recentFile = new File(path);
    try {
            BufferedReader reader = new BufferedReader(newInputStreamReader(newFileInputStream(recentFile), "UTF-8"));
            String temp = reader.readLine();
            reader.close();
            if (temp == null) {System.out.println("your file is empty");}
            else {System.out.println(temp);}
    } catch (IOException ex) {}

txt文件完全是空的,但是当我运行程序时,命令提示符会打印出“?”而不是“你的文件是空的”。

当我将“UTF-8”更改为“Unicode”,并将我的 txt 文件编码格式更改为 Unicode 时,我从提示中得到“您的文件为空”。

为什么我在使用 UTF-8 时会得到这个结果?

顺便说一句,如果这是重复的,请告诉我,我试图在谷歌上搜索多次,但找不到任何对我有帮助的东西。

【问题讨论】:

标签: java utf-8 bufferedreader


【解决方案1】:

文件不是完全空的;这是唯一的解释。最有可能在开头有一个字节顺序标记。这看起来不像一个字符(如果您在记事本中打开文件,它可能会显示为看似完全为空),但它确实很重要。

请注意,我相信 BR 在开始返回 null 之前可能会先返回 1 个空字符串;然而,这不是这里发生的事情(如果是,你就不会看到你的程序打印?)。

您可以使用十六进制编辑器检查实际的字节数。或者,这个 java 代码的 sn-p 会告诉你:

try (var in = new FileInputStream("/path/to/the/file")) {
    for (int c = in.read(); c != -1; c = in.read()) {
       System.out.print("%02X", c & 0xFF);
    }
}
System.out.println();

【讨论】:

    猜你喜欢
    • 2013-04-29
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多