【问题标题】:How to read a file from a certain offset in Java?如何从Java中的某个偏移量读取文件?
【发布时间】:2012-03-29 02:12:30
【问题描述】:

嘿,我正在尝试打开一个文件并仅从偏移量读取一定长度! 我读了这个话题: 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);

是否可以从已知偏移量读取某些字节?

【问题讨论】:

  • 阅读reading files using Java. Seek 方法存在。
  • 您是否设法实施建议的解决方案?我也在尝试做同样的事情,但真的很难。
  • 嗨@kryzystof,是的,我当时用 RandomAccessFile 类(接受的答案)管理了这个。不幸的是,自从 9 年以来,我再也无法访问代码了

标签: java file-io


【解决方案1】:

RandomAccessFile 公开一个函数:

seek(long pos) 
          Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

【讨论】:

  • 这东西是快还是它也只是通过以前的东西?
  • 我想它很快,因为你只是在引用指针。 IIRC 创建了一个跳转表,它应该是 O(1) 时间。
  • 技术上它应该直接跳转,因为单个文件的字节在磁盘上是连续的。
  • @Tudor 我认为没有任何保证,我最后一次阅读有关系统如何写入磁盘的任何信息是在大约 3 年前。
  • @Woot4Moo:确实,如果磁盘碎片严重,您可能会将文件拆分到多个位置,但通常它们应该是连续的。
【解决方案2】:

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 相比如何。

【讨论】:

  • 这似乎是比RandomAccessFile 更灵活的解决方案,因为它允许您返回InputStream 以在您的方法之外进行处理。在 RAF 的情况下,如果您想这样做,您将无法关闭 RAF,从而导致资源泄漏。除非我误解了什么。
猜你喜欢
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多