Java BufferedReader 读取一个空的 txt 文件但不 return null
Java BufferedReader reads an empty txt file but doesn't return null
我尝试使用 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文件完全是空的,但是我运行程序的时候,命令提示符打印出“?”而不是 "your file is empty".
当我将 "UTF-8" 更改为 "Unicode",并将我的 txt 文件编码格式更改为 Unicode 时,我从提示中得到一个 "your file is empty"。
为什么我使用 UTF-8 时会得到这个结果?
顺便说一句,如果这是重复的,请告诉我,我试图在 google 上搜索多次,但找不到任何对我有帮助的东西。
文件未完全清空;这是唯一的解释。最有可能的是在开头有一个字节顺序标记。这看起来不像一个字符(如果你在记事本中打开文件,它可能会显示为看似完全空的),但它确实很重要。
请注意,我相信 BR 可能会先 return 1 个空字符串,然后再开始 returning 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();
我尝试使用 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文件完全是空的,但是我运行程序的时候,命令提示符打印出“?”而不是 "your file is empty".
当我将 "UTF-8" 更改为 "Unicode",并将我的 txt 文件编码格式更改为 Unicode 时,我从提示中得到一个 "your file is empty"。
为什么我使用 UTF-8 时会得到这个结果?
顺便说一句,如果这是重复的,请告诉我,我试图在 google 上搜索多次,但找不到任何对我有帮助的东西。
文件未完全清空;这是唯一的解释。最有可能的是在开头有一个字节顺序标记。这看起来不像一个字符(如果你在记事本中打开文件,它可能会显示为看似完全空的),但它确实很重要。
请注意,我相信 BR 可能会先 return 1 个空字符串,然后再开始 returning 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();