[英]Why does RandomAccessFile read  as firt character in my UTF-8 text file?
關於在 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 編碼的文本文件都具有該標記,但有些具有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.