当前位置:首页 > Java

java如何实现下载

2026-02-04 23:48:26Java

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

java如何实现下载

分享给朋友:

相关文章

vue如何实现tap

vue如何实现tap

实现Tap事件的方法 在Vue中实现类似移动端的tap事件(轻触)可以通过以下几种方式完成。原生移动端浏览器通常通过touchstart和touchend事件组合模拟tap,而Vue中可以封装自定义指…

Vue如何实现多级域名

Vue如何实现多级域名

Vue 实现多级域名的方法 Vue 本身是一个前端框架,多级域名的实现通常需要结合后端配置和前端路由。以下是几种常见的方法: 使用路由动态匹配 在 Vue Router 中可以通过动态路由参数匹配…

java如何创建文件

java如何创建文件

使用 File 类创建文件 通过 File 类的 createNewFile() 方法创建文件。此方法返回布尔值,表示文件是否成功创建。 import java.io.File; import ja…

java如何运行

java如何运行

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

java如何编译

java如何编译

编译Java程序的基本步骤 安装JDK(Java Development Kit)并配置环境变量。确保javac和java命令可在命令行中运行。JDK是编译和运行Java程序的必备工具。 创建Ja…

php如何实现静态化

php如何实现静态化

PHP 实现静态化的方法 使用 ob_start() 和 ob_get_contents() 利用 PHP 的输出缓冲功能捕获动态生成的页面内容,将其保存为静态文件。这种方法适用于内容不频繁变化的页面…