[英]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.