Java

如何在Java中使用URL进行文件下载

小樊
82
2024-09-14 11:20:44
栏目: 编程语言

在Java中,您可以使用java.net.URLjava.io包中的类来下载文件

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

public class FileDownload {
    public static void main(String[] args) {
        String fileURL = "https://example.com/file-to-download.txt"; // 文件下载链接
        String savePath = "downloaded-file.txt"; // 保存到本地的文件名

        try {
            downloadFile(fileURL, savePath);
        } catch (IOException e) {
            System.out.println("Error downloading the file: " + e.getMessage());
        }
    }

    private static void downloadFile(String fileURL, String savePath) throws IOException {
        URL url = new URL(fileURL);
        BufferedInputStream in = new BufferedInputStream(url.openStream());
        FileOutputStream fos = new FileOutputStream(savePath);

        byte[] dataBuffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
            fos.write(dataBuffer, 0, bytesRead);
        }

        // 关闭流
        fos.close();
        in.close();

        System.out.println("File downloaded successfully!");
    }
}

这个示例代码定义了一个downloadFile方法,该方法接受文件的URL和要将其保存到本地的路径。然后,它使用BufferedInputStream从URL读取数据并将其写入FileOutputStream。最后,关闭两个流以释放资源。

请注意,此示例不处理HTTP错误,如重定向或404错误。为了处理这些情况,您需要使用更高级的HTTP客户端库,如Apache HttpClient或OkHttp。

0
看了该问题的人还看了