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


here code

byte data[] = new byte[1024];                 fout = new fileoutputstream(filelocation);                  bytebuffer bb = bytebuffer.allocate(i+i); // size of download               readablebytechannel rbc = channels.newchannel(url.openstream());              while(  (dat = rbc.read(bb)) != -1 )               {                   bb.get(data);                      fout.write(data, 0, 1024); // write data file                   speed.settext(string.valueof(dat));               } 

in code try download file given url, file doesn't complete it's way.

i don't know error happened, readablebytechannel's fault? or didn't put bytes bytebuffer byte[] properly.

when read bytebuffer, offset of buffer changed. means, after read, need rewind bytebuffer:

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

but in case, don't need bytebuffer anyway, using plain byte array enough -- , shorter:

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

note in java 1.7, can use that:

files.copy(url.openstream(), paths.get(filelocation)); 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -