[英]RandomAccessFile to read xml file
我正在尝试使用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和skip()获得随机访问?
您可以使用RandomAccessFile
getChannel()
方法访问文件的一部分。
例如,这里我映射了一个非常大的xml文件(2go)的位置100开始的2000个字节。
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测
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.