2012-07-17 67 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