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[] に正しく配置しませんでした。

4

1 に答える 1

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));
于 2013-07-22T05:31:30.547 に答える