Java将InputStream的一部分复制到OutputStream

时间:2014-03-25 20:47:31

标签: java copy buffer inputstream outputstream

我有一个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 */

我可以逐字节读取和写入,但它会缓慢(我认为)缓冲读取 我该怎么办呢?

1 个答案:

答案 0 :(得分: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);
    }
}

应该适合你。