首页
学习
活动
专区
工具
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中。

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

相关·内容

没有搜到相关的合辑

领券