java - 用java保存文件fiformat pdf文件
问题描述
我正在尝试创建一个pdf文件然后使用fileChooser将其保存到设备它可以保存但是当我去文件打开它时它没有打开这是我的代码
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
fc.setTitle("Save to PDF"
);
fc.setInitialFileName("untitled.pdf");
Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();
File file = fc.showSaveDialog(stg);
if (file != null) {
String str = file.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(str);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close();
writer.close();
fos.flush();
}
当我打开它时,这是显示文件已被其他用户打开或使用的错误
解决方案
close()
您的代码不会FileOutputStream
导致资源泄漏,并且文档无法正确访问,甚至可能已损坏。
当您使用FileOutputStream
thatimplements AutoClosable
时,您有两个选择:
close()
FileOutputStream
手动:
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
fc.setTitle("Save to PDF");
fc.setInitialFileName("untitled.pdf");
Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();
File file = fc.showSaveDialog(stg);
if (file != null) {
String str = file.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(str);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close();
writer.close();
fos.flush();
/*
* ONLY DIFFERENCE TO YOUR CODE IS THE FOLLOWING LINE
*/
fos.close();
}
}
或者使用 a try
with resources read about that in this post例如。
推荐阅读
- sql - 如何在 sql server 2016 中使用没有数组包装器的 json 路径,root('User')
- ios - 推送证书被吊销或过期?
- javascript - 如果在其上使用函数,则无法在 Javascript 中引用动态 $refs [VUE]
- html - 边界半径与虚线之间的自定义空格
- ruby-on-rails - 未初始化的常量 - RoR
- css - 如何在html中制作平滑的缩放效果?
- java - 实现 Comparable 时返回 -1 和 1
在java中 - android - 尝试构建项目时,Android 资源链接失败
- blueprism - RPA Blueprism 发布文件已成功导入但在进程列表中不可见
- java - 如何为特定编码指定字体?