import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PdfDownloader {
public static void main(String[] args) {
String pdfUrl = "http://example.com/path/to/your/pdf.pdf"; // 替换为你的PDF文件的URL
String destinationFile = "path/to/save/pdf.pdf"; // 替换为你希望保存PDF文件的本地路径
try {
URL url = new URL(pdfUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// 总是检查HTTP响应码以确认成功
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = destinationFile;
File file = new File(fileName);
Files.createDirectories(file.getParentFile().toPath());
try (InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[4096];
int bytesRead;
// 将输入流(从URL)写入输出流(到文件)
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("PDF文件已成功下载");
}
} else {
System.out.println("GET请求未成功,响应码为:" + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF下载到本地
最新推荐文章于 2024-08-13 08:43:09 发布
该篇文章详细介绍了如何使用Java编程语言通过HttpURLConnection从指定URL下载PDF文件,包括处理HTTP响应码和文件保存操作。
摘要由CSDN通过智能技术生成