Java BufferedReader读取一个空的txt文件,但不返回n ull

问题描述 投票:0回答:1

我尝试使用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时会得到这个结果?

btw,如果这是重复的邮件,请告诉我,我试图在Google上搜索多次,但找不到对我有帮助的内容。

java utf-8 bufferedreader
1个回答
0
投票

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

请注意,我相信BR可能会先返回1个空字符串,然后再开始返回null;但是,这不是这里发生的情况(如果是这样,您将不会看到程序打印为?)。

您可以使用十六进制编辑器检查实际的字节数。另外,此Java代码段将告诉您:

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();
© www.soinside.com 2019 - 2024. All rights reserved.