当前位置:首页 > Java

java 如何下载文件

2026-03-03 14:12:25Java

使用 Java 下载文件的方法

使用 java.net.URLjava.nio.file.Files

通过 URL 类打开连接,并使用 Files.copy 方法将数据流写入本地文件。

java 如何下载文件

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileDownloader {
    public static void downloadFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        try (InputStream in = url.openStream()) {
            Files.copy(in, Paths.get(savePath));
        }
    }
}

使用 HttpURLConnection 处理 HTTP 请求

对于需要设置请求头或处理 HTTP 响应的场景,HttpURLConnection 更灵活。

java 如何下载文件

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

public class HttpDownloader {
    public static void downloadFile(String fileUrl, String savePath) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");

        try (InputStream in = httpConn.getInputStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}

使用 Apache HttpClient 库

第三方库如 HttpClient 提供更高级的功能,适合复杂场景。

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.FileOutputStream;
import java.io.InputStream;

public class ApacheHttpDownloader {
    public static void downloadFile(String fileUrl, String savePath) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(fileUrl);
            try (CloseableHttpResponse response = client.execute(request)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try (InputStream in = entity.getContent();
                         FileOutputStream out = new FileOutputStream(savePath)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
        }
    }
}

使用 Java 11 的 HttpClient(JDK 内置)

Java 11 引入了新的 HttpClient API,支持异步和非阻塞操作。

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class Java11HttpDownloader {
    public static void downloadFile(String fileUrl, String savePath) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fileUrl))
                .build();
        client.send(request, HttpResponse.BodyHandlers.ofFile(Path.of(savePath)));
    }
}

注意事项

  1. 异常处理:确保捕获 IOException 或其他可能的异常,避免程序崩溃。
  2. 大文件下载:对于大文件,使用缓冲区和分块读写以提高效率。
  3. HTTPS 支持:若下载 HTTPS 链接,需确保 JVM 信任证书或配置 SSL 上下文。
  4. 进度监控:可通过计算已下载字节数与总文件大小的比例实现进度显示。

示例调用

public class Main {
    public static void main(String[] args) {
        try {
            FileDownloader.downloadFile("http://example.com/file.zip", "downloaded.zip");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

分享给朋友:

相关文章

vue实现文件的上传

vue实现文件的上传

文件上传的基本实现 在Vue中实现文件上传通常结合HTML的<input type="file">元素和FormData对象。通过监听文件选择事件获取文件对象,再通过AJAX或axios发…

php实现文件的下载

php实现文件的下载

PHP 实现文件下载的方法 在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,并输出文件内容。以下是几种常见的实现方式: 使用 header() 函数强制下载 通过设置 Conte…

vue文件下载实现

vue文件下载实现

使用 Blob 对象下载文件 在 Vue 中可以通过创建 Blob 对象实现文件下载。通过将后端返回的二进制数据转换为 Blob,再生成下载链接触发浏览器下载行为。 axios.get('/api…

js实现文件的上传

js实现文件的上传

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。HTML部分需要包含一个文件选择控件和一个提交按…

vue 实现文件下载

vue 实现文件下载

使用 window.open 方法 通过 window.open 直接打开文件链接触发下载,适用于已知文件 URL 的情况: window.open('文件URL', '_blank') 使用 &l…

vue预览文件实现

vue预览文件实现

实现文件预览功能 在Vue中实现文件预览功能可以通过多种方式完成,具体取决于文件类型(图片、PDF、文档等)和需求。以下是几种常见实现方法: 图片文件预览 使用HTML5的FileReader A…