如何解决用java保存文件fiormat 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
的{{1}}时,有两个选择:
implements 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();
}
}
,例如,其中的资源与this post中的内容有关。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。