RandomAccessFile读取xml文件
问题描述:
我想用RandomAccessFile读取xml文件。事情是我一次只想读取一定的长度直到文件结束。RandomAccessFile读取xml文件
ReadUTF() read entire lines in the file which I do not want
Read(byte,start,end) seems what I need, but it is readying in byte so it doesnt contain the actual text of the read content.
有没有办法使用RandomAccessFile一次读取一定长度的xml文件?
谢谢。
答
readUTF读取单个UTF编码的字符串,该字符串以无符号的16位长度开头,后面跟着字符串。因此它可以包含许多行,但不能用于读取文本文件。
RandomAccessFile是为二进制格式而设计的,所以很少支持阅读文本。
您是否尝试过使用BufferedReader并跳过()以获得随机访问?
答
您可以使用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