关于用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编码的文本文件都具有该标记,但有些文件具有该标记。