2

我从 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);
4

2 回答 2

5

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();
于 2013-02-16T14:15:43.387 回答
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();
    }
于 2016-07-29T06:26:53.930 回答