返回

如何在 Java 中从互联网下载并保存文件?

java

Java 中从互联网下载并保存文件的完整指南

前言

在 Java 中,从互联网下载并保存文件是一项常见的任务。本文将深入探讨使用 URLConnection 类的最简单方法,并提供详细的步骤和代码示例。

建立 URL 连接

第一步是使用 URL 类创建一个连接到目标文件的 URL。这可以通过以下代码实现:

URL url = new URL("http://www.example.com/information.asp");
URLConnection connection = url.openConnection();

设置连接参数

为了自定义下载行为,可以设置连接参数。例如,可以模拟浏览器请求:

connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");

获取输入流

使用 getInputStream() 方法获取连接的输入流,它包含文件的字节数据:

InputStream inputStream = connection.getInputStream();

创建输出流

接下来,选择一个目录和文件名称,并使用 FileOutputStream 创建一个输出流:

String filePath = "C:/path/to/directory/information.asp";
FileOutputStream fileOutputStream = new FileOutputStream(filePath);

复制文件内容

使用 Apache Commons IO 库中的 IOUtils 类中的 copy() 方法将输入流中的数据复制到输出流中:

IOUtils.copy(inputStream, fileOutputStream);

关闭流

下载完成后,关闭流以释放资源:

inputStream.close();
fileOutputStream.close();

示例代码

以下代码提供了使用 URLConnection 下载和保存文件的完整示例:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;

public class FileDownloader {

    public static void downloadFile(String urlString, String filePath) throws IOException {
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");

        InputStream inputStream = connection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);

        IOUtils.copy(inputStream, fileOutputStream);

        inputStream.close();
        fileOutputStream.close();
    }

    public static void main(String[] args) {
        String urlString = "http://www.example.com/information.asp";
        String filePath = "C:/path/to/directory/information.asp";

        try {
            downloadFile(urlString, filePath);
            System.out.println("File downloaded successfully");
        } catch (IOException e) {
            System.out.println("An error occurred while downloading the file: " + e.getMessage());
        }
    }
}

常见问题解答

1. 如何下载二进制文件?

使用 InputStreamOutputStream 时,不需要明确区分文本文件和二进制文件,因为它们处理字节流。

2. 我能从受密码保护的网站下载文件吗?

可以,但需要向 URLConnection 设置密码信息。

3. 如何处理下载进度?

可以使用 URLConnectiongetContentLength() 方法获取文件大小,然后使用输入流的 available() 方法跟踪下载进度。

4. 存在替代 URLConnection 的方法吗?

可以使用 HTTPClient 库或 Java NIO 进行更高级别的下载操作。

5. 如何从文件 URL 下载文件?

URLConnection 也适用于文件 URL,只需使用 file: 前缀即可,例如 file:///path/to/file.txt

结论

使用 URLConnection 类,你可以轻松、有效地在 Java 中下载并保存文件。本文提供了详细的步骤、代码示例和常见问题解答,帮助你掌握这一技巧。