我的ByteBuffer没有正确地将它的字节放入字节数组中

时间:2013-07-22 04:55:04

标签: java

这是代码

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 []。

1 个答案:

答案 0 :(得分: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));