【发布时间】:2017-11-12 01:06:43
【问题描述】:
我正在尝试从文件“A”中读取字节。我正在使用 RandomAccessFile 来寻找位置,然后我需要读取“y”字节。
我有一个 4096 字节的缓冲区,如果“y”不是 4096 的倍数,我读取的字节数比我应该读的多。
如果我将缓冲区设置为 1 字节,我可以毫无问题地读写(当然,它太慢了)。
我现在的代码是:
public void extractFile(int pos) {
try {
RandomAccessFile raf = new RandomAccessFile(this.archive, "r");
/* Trying to read */
raf.seek(arquivos.get(pos).getPosicaoInicio());
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
byte[] buf = new byte[1]; // With 1 I can read, because every "y" is multiple of 1
byte[] bytes;
while (byteOutput.size() < arquivos.get(pos).getTamanho()) {
byteOutput.write(buf, 0, raf.read(buf));
}
bytes = byteOutput.toByteArray();
byteOutput.close();
raf.close();
/* Writing */
File futuroArquivo = new File(arquivos.get(pos).getNome());
FileOutputStream fos = new FileOutputStream(futuroArquivo);
fos.write(bytes);
fos.flush();
fos.close();
} catch (IOException ex) {
}
}
PS:“arquivos.get(pos).getTamanho()”是我的“y”
PS 2:我无法读取整个文件,因为在“y”字节之后,还有其他内容
【问题讨论】:
标签: java file byte buffer randomaccessfile