Java 我的ByteBuffer没有放置它';将字节正确地放入字节数组
这是密码Java 我的ByteBuffer没有放置它';将字节正确地放入字节数组,java,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.openStre
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的错吗?或者我没有正确地将字节从字节缓冲区放入字节[]。当您读入
字节缓冲区时,缓冲区的偏移量会发生变化。这意味着,在读取之后,您需要将字节缓冲区倒带
:
while ((dat = rbc.read(bb)) != -1) {
fout.write(bb.array(), 0, bb.position());
bb.rewind(); // prepare the byte buffer for another read
}
但在您的情况下,实际上并不需要字节缓冲符
,只要使用普通字节数组就足够了,而且它更短:
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));
尝试使用fout.flush();fout.close()
在fout.write()之后@Prabhaker.close()应该在那里吗?因为这可能意味着我将无法再在循环中使用通道。抱歉,我不是指在循环中。您可以在循环后使用close()(当使用完成时,您必须关闭它们);为什么要使用第二个字节数组,而用字节缓冲区分配一个呢?同样,这是Java 1.7吗?