2013-07-22 46 views
0

下面是代碼我的字節緩衝區沒有把它的字節到字節數組正確

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

      } 

在這段代碼我嘗試從給定的URL下載一個文件,但該文件沒有完成所有它的方式。

我不知道發生了什麼錯誤,是ReadableByteChannel的錯嗎?或者我沒有正確地將ByteBuffer的字節放入Byte []中。

+0

使用'fout.flush()嘗試; fout.close();'fout.write後'()' – Prabhaker

+0

@Prabhaker應該.close( )在那裏?因爲這可能意味着我將無法在循環中使用該通道。 – user2519193

+0

對不起,我不是在循環中的意思。你可以在循環後使用close()(當你的使用完成時你必須關閉它們); – Prabhaker

回答

2

當您讀入ByteBuffer時,緩衝區的偏移量會發生變化。這意味着,讀取後,需要倒帶ByteBuffer

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

但在你的情況,你並不真的需要一個ByteBuffer無論如何,只是使用普通的字節數組是不夠的 - 它是短:

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

注意,在Java中1.7,你可以使用:

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

你寫的第一個代碼效果很好! 謝謝! – user2519193