【问题标题】:(JAVA) Read "buffer" bytes (or "y" bytes if (y < buffer)) from a file(JAVA)从文件中读取“缓冲区”字节(或“y”字节,如果(y <缓冲区))
【发布时间】: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


【解决方案1】:

缓冲区可以是大于零的任何大小,ByteArrayOutputStream 确实是在浪费时间。和空间。您假设 read() 也填充了缓冲区。更好的写法是:

RandomAccessFile raf = new RandomAccessFile(this.archive, "r");

/* Trying to read */
raf.seek(arquivos.get(pos).getPosicaoInicio());
byte[] buf = new byte[8192]; // or more, whatever you like really

/* Writing */
File futuroArquivo = new File(arquivos.get(pos).getNome());
FileOutputStream fos = new FileOutputStream(futuroArquivo);
int count;
long rest = arquivos.get(pos).getTamanho();
while (rest > 0 && (count = raf.read(buf, 0, (int)Math.min(buf.length, rest))) > 0)
{
    fos.write(buf, 0, count);
    rest -= count;
}
fos.close();
raf.close();

我还会考虑为此使用BufferedInputStream 围绕FileInputStream,而不是RandomAccessFile。您实际上并不是在进行随机访问,而只是初始搜索或跳过。

【讨论】:

  • 为了清楚起见,我认为您应该将rest &gt; 0 &amp;&amp; 添加到while 条件中。无论如何 +1。
  • @Andreas 同意。当rest == 0 时,我不打算依赖read() 返回零。
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
相关资源
最近更新 更多