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







