Java

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

小亿
160
2023-11-28 04:08:18
栏目: 编程语言

要在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流中的数据,并将其写入本地文件,直到达到流的末尾。

0
看了该问题的人还看了