4

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
  • I want to copy part of an InputStream to OutputStream Commented Mar 25, 2014 at 21:05

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

should work for you.

Sign up to request clarification or add additional context in comments.

3 Comments

bytesRead<=end just check while step readed bytes be <= than end not all readed bytes.
yes @Curious it will dispose of the first bytes and then uses a buffer of 1024 bytes to write the outputstream You might also check out the Channel class.
Your start argument is actually the number of bytes to skip before copying and it would be more efficient to do that with input.skip(start);
1

If you have access to the Apache Commons library, you can use:

IOUtils.copyLarge(InputStream input, OutputStream output, long inputOffset, long length)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.