如何从Java中的某个偏移量读取文件?
嘿我正在尝试打开一个文件并从偏移中读取一定长度! 我读了这个主题: 如何使用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
比较。