user2519193
user2519193

Reputation: 211

My ByteBuffer is not placing it's bytes into a bytes array properly

Here is the code

byte data[] = new byte[1024];
                fout = new FileOutputStream(fileLocation);

                ByteBuffer bb = ByteBuffer.allocate(i+i); // i is size of download
              ReadableByteChannel rbc = Channels.newChannel(url.openStream());
             while(  (dat = rbc.read(bb)) != -1 )

             {

                 bb.get(data);

                    fout.write(data, 0, 1024); // write the data to the file

                 speed.setText(String.valueOf(dat));

             }

In this code I try to download a file from a given URL, but the file doesn't complete all it's way.

I don't know what error happened, is it the ReadableByteChannel's fault? Or I didn't put my bytes from the ByteBuffer into the Byte[] properly.

Upvotes: 0

Views: 182

Answers (1)

fge
fge

Reputation: 121702

When you read into a ByteBuffer, the offset of the buffer is changed. Which means, after the read, you need to rewind the ByteBuffer:

while ((dat = rbc.read(bb)) != -1) {
    fout.write(bb.array(), 0, bb.position());
    bb.rewind(); // prepare the byte buffer for another read
}

But in your case, you don't really need a ByteBuffer anyway, just using a plain byte array is enough -- and it is shorter:

final InputStream in = url.openStream();
final byte[] buf = new byte[16384];
while ((dat = in.read(buf)) != -1)
    fout.write(buf, 0, dat);

Note that in Java 1.7, you can use that:

Files.copy(url.openStream(), Paths.get(fileLocation));

Upvotes: 2

Related Questions