您可以使用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