2012-07-17 70 views
0

我想用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文件?

谢谢。

+1

wh你是否想这样做? XML不完全是随机访问格式。 – jtahlborn 2012-07-17 15:41:11

回答

0

readUTF读取单个UTF编码的字符串,该字符串以无符号的16位长度开头,后面跟着字符串。因此它可以包含许多行,但不能用于读取文本文件。

RandomAccessFile是为二进制格式而设计的,所以很少支持阅读文本。

您是否尝试过使用BufferedReader并跳过()以获得随机访问?

0

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

+0

这只适用于以下情况:1.您使用的字符编码与xml文件的编码匹配; 2.它是单字节编码。风险至多... – jtahlborn 2012-07-17 16:24:32

+0

@jtahlborn用户必须知道他的文件的编码是。但它不仅适用于单字节编码。看看编辑。 – 2012-07-17 16:58:00

+0

您的编辑仅适用于utf-16编码,因为您已正确选择了开始边界。但是,如果您开始使用奇数字节,则会被破坏。如果你使用的是utf-8,那么选择一个“正确”的起始字节是不可能的。 – jtahlborn 2012-07-17 17:03:41