一个关于用Java读取文本文件的问题。我有一个使用 UTF-8 编码保存的文本文件,其中仅包含内容:
你好。世界。
现在我使用 RandomAccessFile
来读取此类。但由于某种原因,文件开头似乎有一个“看不见”的字符......?
我使用这个代码:
File file = new File("resources/texts/books/testfile2.txt");
try(RandomAccessFile reader = new RandomAccessFile(file, "r")) {
String readLine = reader.readLine();
String utf8Line = new String(readLine.getBytes("ISO-8859-1"), "UTF-8" );
System.out.println("Read Line: " + readLine);
System.out.println("Real length: " + readLine.length());
System.out.println("UTF-8 Line: " + utf8Line);
System.out.println("UTF-8 length: " + utf8Line.length());
System.out.println("Current position: " + reader.getFilePointer());
} catch (Exception e) {
e.printStackTrace();
}
输出是这样的:
Read Line: ?»?Hello. World.
Real length: 16
UTF-8 Line: ?Hello. World.
UTF-8 length: 14
Current position: 16
这些(1或2)个字符似乎只出现在开头。如果我向文件添加更多行并读取它们,那么所有其他行都会正常读取。 有人可以解释这种行为吗?这个开头的字符是什么?
谢谢!
最佳答案
文件中的前 3 个字节(0xef
、0xbb
、0xbf
)称为 UTF-8 BOM(字节顺序标记)。 BOM 仅对 UTF-16 和 UTF-32 很重要 - 对于 UTF-8 它没有任何意义。微软引入它是为了更好地猜测文件编码。
也就是说,并非所有 UTF-8 编码的文本文件都有该标记,但有些文件有。
关于java - 为什么随机访问文件在我的 UTF-8 文本文件中读取“ï”作为第一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52098792/