[英]How to read a file from a certain offset in Java?
嘿,我正在嘗試打開一個文件並從一定長度的偏移量中讀取! 我閱讀了這個主題: How to read a specific line using the specific line number from a file in Java? 在那里它說不可能在不閱讀之前閱讀某一行的情況下閱讀某一行,但我想知道字節!
FileReader location = new FileReader(file);
BufferedReader inputFile = new BufferedReader(location);
// Read from bytes 1000 to 2000
// Something like this
inputFile.read(1000,2000);
是否可以從已知偏移量讀取某些字節?
RandomAccessFile公開一個函數:
seek(long pos)
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
FileInputStream.getChannel().position(123)
除了RandomAccessFile
之外,這是另一種可能性:
File f = File.createTempFile("aaa", null);
byte[] out = new byte[]{0, 1, 2};
FileOutputStream o = new FileOutputStream(f);
o.write(out);
o.close();
FileInputStream i = new FileInputStream(f);
i.getChannel().position(1);
assert i.read() == out[1];
i.close();
f.delete();
這應該沒問題,因為FileInputStream#getChannel
的文檔說:
顯式或通過讀取更改通道的位置將更改此流的文件位置。
但是,我不知道這種方法與RandomAccessFile
相比如何。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.