从HTTP服务器下载文件时遇到一些问题。下面的代码只下载~30MB的文件(文件大小为52MB)。我的浏览器下载文件没有任何问题。有什么问题?
URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
答案 0 :(得分:4)
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();
答案 1 :(得分:0)
try {
InputStream inputStream = url.openStream();
ReadableByteChannel rbc = Channels.newChannel(inputStream);
FileOutputStream fos = new FileOutputStream("your-pc-path");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}