繁体   English   中英

如何从Java中的某个偏移量读取文件?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM