FileChannel.transferFrom() Java 文档说:
将字节从给定的可读字节通道传输到此通道的文件中。
尝试从源通道读取 count 个字节并将它们从给定位置开始写入此通道的文件。此方法的调用可能会也可能不会传输所有请求的字节;是否这样做取决于通道的性质和状态。如果源通道剩余的字节数少于计数,或者源通道是非阻塞的并且其输入缓冲区中立即可用的字节数少于计数,则将传输少于请求的字节数。
URL website = new URL("http://www.website.com/information.asp");
URLConnection connection = website.openConnection();
ReadableByteChannel rbc = Channels.newChannel( connection.getInputStream());
FileOutputStream fos = new FileOutputStream("information.html" );
long expectedSize = connection.getContentLength();
System.out.println( "Expected size: " + expectedSize );
long transferedSize = 0L;
while( transferedSize < expectedSize ) {
transferedSize +=
fos.getChannel().transferFrom( rbc, transferedSize, 1 << 24 );
System.out.println( transferedSize + " bytes received" );
}
fos.close();