为什么随机访问文件读取  作为我的 UTF-8 文本文件中的第一个字符?
Why does RandomAccessFile read  as firt character in my UTF-8 text file?
关于阅读 Java 中的文本文件的问题。我有一个用 UTF-8 编码保存的文本文件,只有内容:
您好。世界.
现在我正在使用 RandomAccessFile
阅读此 class。但是不知道为什么,文件开头好像有一个"invisible"字符...?
我使用这个代码:
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 它没有任何意义。 Microsoft 引入它是为了更好地猜测文件编码。
也就是说,并非所有 UTF-8 编码的文本文件都有该标记,但有些文件有。
关于阅读 Java 中的文本文件的问题。我有一个用 UTF-8 编码保存的文本文件,只有内容:
您好。世界.
现在我正在使用 RandomAccessFile
阅读此 class。但是不知道为什么,文件开头好像有一个"invisible"字符...?
我使用这个代码:
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 它没有任何意义。 Microsoft 引入它是为了更好地猜测文件编码。
也就是说,并非所有 UTF-8 编码的文本文件都有该标记,但有些文件有。