Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中如何从某个偏移量读取文件?_Java_File Io - Fatal编程技术网

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

在Java中如何从某个偏移量读取文件?,java,file-io,Java,File Io,嘿,我正试图打开一个文件,从偏移量读取一定长度的数据! 我读过这个话题: 在那里,它说不可能在没有阅读之前就阅读某一行,但我想知道字节 FileReader location = new FileReader(file); BufferedReader inputFile = new BufferedReader(location); // Read from bytes 1000 to 2000 // Something like this inputFile.read(1000,2000);

嘿,我正试图打开一个文件,从偏移量读取一定长度的数据! 我读过这个话题: 在那里,它说不可能在没有阅读之前就阅读某一行,但我想知道字节

FileReader location = new FileReader(file);
BufferedReader inputFile = new BufferedReader(location);
// Read from bytes 1000 to 2000
// Something like this
inputFile.read(1000,2000);
是否可以从已知偏移量读取某些字节?

公开一个函数:

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)

这是除了
随机访问文件
之外的另一种可能性:

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();
这应该没问题,因为的文档说明:

显式或通过读取更改通道的位置将更改此流的文件位置


我不知道该方法与
RandomAccessFile
相比如何。

了解
Seek
方法的存在。您是否成功实施了建议的解决方案?我也在试着这么做,但真的很难。嗨@kryzystof,是的,我当时用RandomAccessFile类(公认的答案)处理了这个问题。不幸的是,我已经9年没有访问代码了,这东西快吗?或者它也只是浏览了前面的代码?我想它很快,因为你只是在引用指针。IIRC创建了一个排序跳转表,它应该是O(1)次。从技术上讲,它应该直接跳转,因为单个文件的字节在磁盘上是连续的。@Tudor我认为没有任何保证,但我上次读到关于系统如何写入磁盘的任何信息大约是在3年前。@Woot4Moo:的确,如果磁盘碎片严重,您可能会将文件拆分到多个位置,但通常情况下,这些文件应该是连续的。这似乎是一个比
RandomAccessFile
更灵活的解决方案,因为它允许您返回
InputStream
,以便在方法之外进行处理。在英国皇家空军的情况下,如果您想这样做,您将无法关闭英国皇家空军,从而导致资源泄漏。除非我误解了什么。