Java copy part of InputStream to OutputStream

Deadly 提交于 2020-01-13 04:47:13

问题


I have a file with 3236000 bytes and I want to read 2936000 from start and write to an 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 */

I can read and write byte by byte, but it's to slow (i think) from buffered reading How can do I copy it?


回答1:


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);
    }
}

should work for you.



来源:https://stackoverflow.com/questions/22645895/java-copy-part-of-inputstream-to-outputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!