Java将InputStream的一部分复制到OutputStream

4
我有一个文件,大小为3236000字节,我想从开头读取2936000字节并写入OutputStream。
InputStream is = new FileInputStream(file1);
OutputStream os = new FileOutputStream(file2);

AFunctionToCopy(is,os,0,2936000); /* a function or sourcecode to write input stream 0to2936000 bytes */

我可以逐字节地读写,但是从缓冲读取可能会太慢了(我认为)。那么如何进行拷贝呢?


我想将InputStream的一部分复制到OutputStream中。 - Curious
2个回答

2
public static void copyStream(InputStream input, OutputStream output, long start, long end)
    throws IOException
{
    for(int i = 0; i<start;i++) input.read(); // dispose of the unwanted bytes
    byte[] buffer = new byte[1024]; // Adjust if you want
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1 && bytesRead<=end) // test for EOF or end reached
    {
        output.write(buffer, 0, bytesRead);
    }
}

应该适用于您。


bytesRead<=end 只需检查当步骤读取的字节数小于等于结束时,而不是所有已读取的字节数。 - Curious
是的,@Curious 它会处理掉前面的字节,然后使用1024字节的缓冲区来写入输出流。你也可以查看Channel类。 - nimsson
1
你的 start 参数实际上是在复制之前要跳过的字节数,使用 input.skip(start); 更有效率。 - MasterHD

1
如果您可以访问Apache Commons库,您可以使用以下方法:
IOUtils.copyLarge(InputStream input, OutputStream output, long inputOffset, long length)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接