Java 保存 PDF 文件流到本地:完整代码示例
您可以使用 Java 的文件输入输出流将 PDF 文件流保存到本地。以下是一个示例代码:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SavePDFToFile {
public static void savePDF(InputStream pdfStream, String filePath) throws IOException {
try (OutputStream outputStream = new FileOutputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = pdfStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}
public static void main(String[] args) {
InputStream pdfStream = // 获取PDF文件流的代码,例如从网络下载或从其他来源获取
String filePath = 'path/to/save/file.pdf';
try {
savePDF(pdfStream, filePath);
System.out.println('PDF文件保存成功!');
} catch (IOException e) {
System.out.println('保存PDF文件时发生错误:' + e.getMessage());
}
}
}
在上面的代码中,savePDF方法接收一个InputStream类型的PDF文件流和要保存到的文件路径作为参数。它使用文件输出流将数据从输入流写入到本地文件。在main方法中,您可以调用savePDF方法并传入您获取到的PDF文件流和要保存到的文件路径。
请注意,您需要根据实际情况自行获取PDF文件流,例如从网络下载或从其他来源获取。
原文地址: https://www.cveoy.top/t/topic/qzg0 著作权归作者所有。请勿转载和采集!