在 Java 中实现文件下载是一个常见的需求,尤其是在开发 Web 应用程序时。本文将详细介绍如何使用 Java 实现文件下载功能,涵盖从本地文件系统下载文件以及通过 HTTP 下载文件的两种场景。
1. 从本地文件系统下载文件
如果文件存储在本地文件系统中,可以通过 Java 的 InputStream 和 OutputStream 实现文件下载。
1.1 示例代码
以下是一个简单的示例,展示如何从本地文件系统下载文件:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDownloadExample {
public static void downloadFile(String filePath, OutputStream outputStream) throws IOException {
Path path = Paths.get(filePath);
File file = path.toFile();
if (!file.exists()) {
throw new IOException("File not found: " + filePath);
}
try (FileInputStream fileInputStream = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead)