问题描述
我正在尝试创建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中的内容有关。