Java

java怎么通过url下载文件

小亿
105
2024-02-04 15:44:52
栏目: 编程语言

在Java中,可以使用java.net.URL类来下载文件。下面是一个简单的示例代码:

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

public class FileDownloader {
    public static void downloadFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        BufferedInputStream inputStream = new BufferedInputStream(url.openStream());
        FileOutputStream outputStream = new FileOutputStream(savePath);

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

        outputStream.close();
        inputStream.close();
    }

    public static void main(String[] args) {
        String fileUrl = "https://example.com/file.txt";
        String savePath = "/path/to/save/file.txt";

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

在上面的示例代码中,downloadFile方法接受文件的URL和保存的路径作为参数,通过URL类打开输入流并使用BufferedInputStream进行缓冲读取,然后使用FileOutputStream写入到指定的文件中。最后,关闭输入流和输出流。

main方法中,你可以替换fileUrlsavePath为你要下载的文件的URL和保存的路径。

0
看了该问题的人还看了