java.nio.file.FileSystemException移动文件时

时间:2015-12-28 16:55:35

标签: java pdfrenderer

我尝试使用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()或两者,没有运气。 我不知道锁定我的文件是什么。 我该如何解决?。

1 个答案:

答案 0 :(得分:0)

你能尝试在convertPDFtoImage方法之外移动吗?这样它应该更干净,因为raf,channel都是方法的本地。