当前位置:首页 > Java

java如何实现下载

2026-02-04 23:48:26Java

使用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应用场景。

分享给朋友:

相关文章

h5如何实现vr效果

h5如何实现vr效果

使用WebXR API实现VR效果 WebXR是浏览器中实现VR/AR的核心API,支持设备姿态追踪、渲染交互等功能。需在支持WebXR的设备(如Oculus、HTC Vive)或浏览器模拟环境中运行…

vue如何实现登录

vue如何实现登录

Vue 实现登录功能的方法 创建登录表单组件 在 Vue 项目中创建一个登录表单组件,通常命名为 Login.vue。表单包含用户名和密码输入框,以及提交按钮。 <template>…

vue如何实现原理

vue如何实现原理

Vue 实现原理的核心机制 Vue.js 的核心实现原理基于响应式系统、虚拟 DOM 和组件化设计。以下是关键机制的详细解析: 响应式系统 Vue 通过 Object.defineProperty(…

vue如何实现单选

vue如何实现单选

使用原生 HTML 单选按钮 在 Vue 中可以直接使用 HTML 的原生单选按钮,通过 v-model 绑定数据。 <template> <div>…

如何安装java环境

如何安装java环境

下载JDK安装包 访问Oracle官方网站或OpenJDK项目页面,选择适合操作系统的JDK版本(如Windows、macOS或Linux)。确保下载与系统架构匹配的版本(32位或64位)。 运行安…

vue如何实现select

vue如何实现select

Vue 实现 Select 组件的方法 在 Vue 中实现 Select 组件可以通过原生 HTML <select> 元素或使用第三方 UI 库(如 Element UI、Ant Des…