嘿,我正在尝试打开一个文件,并从一个偏移量读取一定长度!我读了这个主题: 如何使用Java中的文件中的特定行号读取特定行? 在那里,它说不能读取某一行而不读取之前的行,但我想知道字节!
FileReader location = new FileReader(file);
BufferedReader inputFile = new BufferedReader(location);
// Read from bytes 1000 to 2000
// Something like this
inputFile.read(1000,2000);
Run Code Online (Sandbox Code Playgroud)
是否可以从已知偏移中读取某些字节?
Woo*_*Moo 21
RandomAccessFile公开一个函数:
seek(long pos)
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
Run Code Online (Sandbox Code Playgroud)
Cir*_*四事件 11
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();
Run Code Online (Sandbox Code Playgroud)
这应该没问题,因为文档FileInputStream#getChannel说:
通过显式或通过读取更改通道的位置将更改此流的文件位置.
但是我不知道这种方法的比较RandomAccessFile.