Q:

Copy a file from n-number of bytes to n-number of bytes buffered

Consider this code:
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("/home/gala/falken_test/test_file"));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("/home/gala/falken_test/out"));

int b;
byte[] buff = new byte[8096];
while ((b = bufferedInputStream.read(buff)) > -1) {
    bufferedOutputStream.write(buff, 0, b);
    System.out.println("Writing " + b);
}

bufferedInputStream.close();
bufferedOutputStream.close();

This copies a file from point A (bufferedInputStream) to point B (bufferedOutputStream), 8096 bytes at a time, untill the last try is larger than the file itself, then it trims the buffer and reads the remaining data. This looks like this, this is the output from System.out.println("Writing " + b);
Writing 8096
Writing 8096

    ...

Writing 8096
Writing 8096
Writing 5681

This took 14 ms

Now the problem rises that, how can I copy a certain range of bytes?
For example, from 1012 bytes to 2134, if the file is 10000 bytes long for example.
What I an writing is a tar implementation, where a lot of files get concatenated one to other with a 512 byte header between them, which describes the bytes following the header.
And I read the header, skip 512 bytes of the header and start writing the file, until n-bytes of data, which are specified in the header.
How can I solve this without copying byte-by-byte?

A:

You can use BufferedInputStream.skip(long) to skip until right pos, and the read and write the amount of bytes from 1012 (startPos) to 2134 (endPos), that is 2134-1012=1122 bytes.
Note: I changed the buffer size to 512 instead to show how it works with your example positions.
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("test_file"));
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("test_out"));

    int CHUNK_SIZE = 512; // change to 8096
    int startPos = 1012;
    int endPos = 2134;
    int bytesToRead = endPos - startPos;
    int b;
    byte[] buff = new byte[CHUNK_SIZE];
    bufferedInputStream.skip(startPos - 1);
    int currentChunkSize = Math.min(CHUNK_SIZE, bytesToRead);
    while ((b = bufferedInputStream.read(buff, 0, currentChunkSize)) != -1) {
        bufferedOutputStream.write(buff, 0, b);
        System.out.println("Writing " + b);
        bytesToRead -= b;
        if (bytesToRead == 0) {
            break;
        }
        currentChunkSize = Math.min(CHUNK_SIZE, bytesToRead);
    }

    bufferedInputStream.close();
    bufferedOutputStream.close();

The output from this is:
$ java -cp ReadWriteTest    
Writing 512
Writing 512
Writing 98

