您可以使用RandomAccessFile
的方法getChannel()
訪問文件的一部分。
例如,我在這裏映射2000個字節,從一個非常大的xml文件(2go)的位置100開始。
FileChannel channel = new RandomAccessFile("frwiktionary-20120216-pages-meta-current.xml", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 100, 2000);
//Change the value with the proper encoding
Charset chars = Charset.forName("ISO-8859-1");
CharBuffer cbuf = chars.decode(buffer);
System.out.println("buffer = " + cbuf);
編輯(參見下面註釋)
它不僅與單字節編碼的工作原理,請參閱本試驗:
FileOutputStream fop = new FileOutputStream("/home/alain/Bureau/utf16.txt");
try (OutputStreamWriter wr = new OutputStreamWriter(fop, "UTF-16")) {
wr.write("test test toto 測");
}
FileChannel channel = new RandomAccessFile("/home/alain/Bureau/utf16.txt", "r").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
Charset chars = Charset.forName("UTF-16");
CharBuffer cbuf = chars.decode(buffer);
System.out.println("buffer = " + cbuf);
輸出:
緩衝液=試驗測試toto測
wh你是否想這樣做? XML不完全是隨機訪問格式。 – jtahlborn 2012-07-17 15:41:11