首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用InputStream下载大文件

在Java中,你可以使用InputStream来下载大文件

代码语言:javascript
复制
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class FileDownloader {

    public static void main(String[] args) {
        String fileUrl = "https://example.com/largefile.zip";
        String destinationFile = "downloaded_largefile.zip";

        try {
            downloadFile(fileUrl, destinationFile);
            System.out.println("文件下载完成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downloadFile(String fileUrl, String destinationFile) throws Exception {
        URL url = new URL(fileUrl);
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        ReadableByteChannel readableByteChannel = null;

        try {
            inputStream = new BufferedInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(destinationFile);
            readableByteChannel = Channels.newChannel(inputStream);

            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = readableByteChannel.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
        } finally {
            if (readableByteChannel != null) {
                try {
                    readableByteChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这个示例中的downloadFile方法接受一个文件URL和一个目标文件路径作为参数。它首先创建一个URL对象,然后打开一个InputStream。接下来,它创建一个FileOutputStream和一个ReadableByteChannel,并将InputStream的内容读取到FileOutputStream中。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

10分13秒

6.使用 Utils下载大文件.avi

6分1秒

113.okhttp-utils 大文件下载.avi

6分5秒

12.使用 xUtils3 大文件上传.avi

3分47秒

使用抓包工具下载直播回放视频

4分13秒

【Android开发基础】入门,下载使用Android Studio

1.3K
11分36秒

09.使用 xUtils3 文件下载.avi

4分20秒

【玩转腾讯云】使用对象存储提供文件下载服务

2分43秒

Codeblocks最新版免安装版本下载使用教程

5分16秒

python源码打包上传到pypi供大家下载使用

3分26秒

10.使用 xUtils3 文件断点续传下载.avi

1分15秒

如何编写一个使用Objective-C的下载器程序

1分4秒

使用Go语言和colly库来下载指定网站图片的程序

领券