0
我正在嘗試使用文件通道來讀取一個大型的xml文件,這裏的示例代碼我發現3210。當我嘗試它時,它打印出不可識別的字符: import java.io.File; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel;使用文件通道讀取文本文件返回非法字符
public class MainClass {
public static void main(String[] args) throws Exception {
File aFile = new File("charData.xml");
FileInputStream inFile = null;
inFile = new FileInputStream(aFile);
FileChannel inChannel = inFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);
while (inChannel.read(buf) != -1) {
System.out.println("String read: " + ((ByteBuffer) (buf.flip())).asCharBuffer().get(0));
buf.clear();
}
inFile.close();
}
}
輸出:
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
String read: ⸮
你錯過了什麼嗎? 謝謝,
大衛
這個作品,謝謝!另一個問題:這裏的字節大小是否重要。如果我增加它會提高性能嗎? –
實際上,它在某種意義上沒有更多無法識別的字符,但它不是按行讀取文件行 –
@DavidZhao但問題是爲什麼它返回垃圾字符,我已經解決了。 –