java下载文件到本地怎么实现

864
2023/11/20 4:08:18
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在Java中将文件下载到本地,可以使用Java的URL类和InputStream类来实现。下面是一个简单的示例代码:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class FileDownloader {
    public static void main(String[] args) {
        String fileUrl = "https://example.com/file.txt";
        String savePath = "C:\\downloads\\file.txt";

        try {
            downloadFile(fileUrl, savePath);
            System.out.println("文件下载成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void downloadFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        try (InputStream inputStream = url.openStream();
             FileOutputStream outputStream = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}

在上面的示例中,fileUrl是要下载的文件的URL地址,savePath是要保存到本地的路径。downloadFile方法使用URL类打开URL流,并使用FileOutputStream类将文件写入本地。通过循环读取URL流中的数据,并将其写入本地文件,直到达到流的末尾。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: idea怎么运行单个java文件