当前位置:首页 > 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项目实现步骤 环境搭建 确保已安装Node.js和npm。使用Vue CLI创建项目: npm install -g @vue/cli vue create my-project cd my-…

vue如何实现id

vue如何实现id

在 Vue 中实现 ID 绑定 Vue 提供了多种方式为元素或组件绑定唯一的 ID,可以根据具体需求选择合适的方法。 方法一:使用 v-bind 绑定静态或动态 ID <template&g…

java如何自学

java如何自学

确定学习目标和路径 自学Java需要明确目标,例如开发Web应用、Android应用或后端服务。根据目标选择学习重点,如Java基础、Spring框架或Android开发。制定阶段性计划,从基础语法到…

如何编译java

如何编译java

安装JDK 确保系统已安装Java Development Kit(JDK)。可通过命令行输入 javac -version 和 java -version 验证是否安装成功。若未安装,需从Oracl…

java如何解决高并发

java如何解决高并发

Java 高并发解决方案 使用线程池优化资源管理 线程池(如 ThreadPoolExecutor)能避免频繁创建和销毁线程的开销。通过核心线程数、最大线程数和任务队列的合理配置,可以平衡系统负载。例…

java如何打印数组

java如何打印数组

打印数组的方法 在Java中,打印数组有多种方式,以下是几种常见的方法: 使用Arrays.toString()方法 这种方法适用于一维数组,可以快速将数组转换为字符串形式输出: int[] a…