当前位置:首页 > Java

java如何实现下载

2026-02-04 23:48:26Java

java如何实现下载

java如何实现下载

使用Java实现文件下载

Java可以通过多种方式实现文件下载功能,以下是几种常见的方法:

使用HttpURLConnection下载文件

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

public class FileDownloader {
    public static void downloadFile(String fileURL, String saveDir) throws Exception {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");

            if (disposition != null) {
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10, disposition.length() - 1);
                }
            } else {
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
            }

            InputStream inputStream = httpConn.getInputStream();
            String saveFilePath = saveDir + File.separator + fileName;

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

            outputStream.close();
            inputStream.close();
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }
}

使用Apache 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.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class HttpClientDownloader {
    public static void downloadFile(String fileURL, String saveDir) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(fileURL);
        CloseableHttpResponse response = httpClient.execute(httpGet);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
            File file = new File(saveDir + File.separator + fileName);

            try (InputStream inputStream = entity.getContent();
                 FileOutputStream outputStream = new FileOutputStream(file)) {
                int bytesRead;
                byte[] buffer = new byte[4096];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        }
        response.close();
        httpClient.close();
    }
}

使用Java NIO下载文件

import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NioFileDownloader {
    public static void downloadFile(String fileURL, String savePath) throws IOException {
        URL url = new URL(fileURL);
        try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
             FileChannel fileChannel = FileChannel.open(Paths.get(savePath), 
                 StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
            fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
        }
    }
}

使用Spring Boot实现文件下载

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileDownloadController {
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filePath) throws MalformedURLException {
        Path path = Paths.get(filePath);
        Resource resource = new UrlResource(path.toUri());

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
}

文件下载的注意事项

  • 处理大文件时使用缓冲区提高性能
  • 检查目标目录是否存在并具有写入权限
  • 处理网络连接中断等异常情况
  • 考虑显示下载进度
  • 对于敏感文件实现权限验证
  • 设置适当的超时时间防止长时间阻塞

以上方法可以根据具体需求选择使用,HttpURLConnection是Java标准库提供的解决方案,Apache HttpClient提供了更丰富的功能,Java NIO适合处理大文件下载,Spring Boot方案适合Web应用场景。

分享给朋友:

相关文章

vue底层如何实现

vue底层如何实现

Vue 底层的核心实现机制 Vue 的底层实现主要围绕响应式系统、虚拟 DOM 和组件化架构展开。以下是关键技术的详细解析: 响应式系统 依赖追踪与发布订阅模式 通过 Object.definePr…

java如何运行

java如何运行

运行Java程序的基本方法 Java程序的运行需要经过编写、编译和执行三个主要阶段。以下是具体步骤: 编写Java源代码 创建一个以.java为后缀的文件,例如HelloWorld.java。文件内…

java如何编程

java如何编程

Java编程基础 Java是一种面向对象的编程语言,广泛应用于企业级开发、移动应用(Android)等领域。以下是Java编程的核心步骤和示例。 环境搭建 安装JDK 从Oracle官网下载适合…

如何学java

如何学java

学习Java的基础知识 Java是一门面向对象的编程语言,掌握基础语法是入门的关键。需要了解变量、数据类型、运算符、控制结构(如if-else、for循环、while循环)、数组等概念。可以通过官方文…

如何编写java

如何编写java

编写Java程序的基本步骤 安装Java开发工具包(JDK),确保系统环境变量配置正确。可以从Oracle官网下载最新版本的JDK并进行安装。 选择一个合适的集成开发环境(IDE),如Eclipse…

java如何获取当前时间

java如何获取当前时间

获取当前时间的方法 在Java中,可以通过多种方式获取当前时间。以下是几种常见的方法: 使用 java.util.Date Date currentDate = new Date(); Syste…