我正在尝试使用 pdf-renderer 从 pdf 文件的最后一页创建图像。没问题。但创建图像后,我想将原始 pdf 文件移动到新文件夹,但总是失败。
java.nio.file.FileSystemException: D:\test.pdf -> D:\folder\test.pdf: 该进程无法访问该文件,因为它正被另一个进程使用。
这是我的示例代码:
private String convertPDFtoImage(String myFile, String lokasiAwal, String lokasiBaru) {
try {
File pdfFile = new File(myFile);
RandomAccessFile raf = new RandomAccessFile(pdfFile, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdf = new PDFFile(buf);
Integer lastPage = pdf.getNumPages();
PDFPage page = pdf.getPage(lastPage);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
int width = rect.width;
int height = rect.height;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Image image = page.getImage(width, height, rect, null, true, true);
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
String newImage = System.getProperty("user.home")+"/images/test.png";
BufferedImage dest = bufferedImage.getSubimage(0, 0, width, height);
ImageIO.write(dest, "png", new File(newImage));
raf.close();
Files.move(Paths.get(lokasiAwal), Paths.get(lokasiBaru));
return newImage;
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
我认为这是因为我的应用程序仍在使用该文件。我已经尝试过 raf.close() 或 channel.close() 或两者,没有运气。我不知道是什么锁定了我的文件。我该如何解决?