开发者社区> 问答> 正文

Java中将pdf文件转成image后,pdf文件删除失败,怎么回事? 400 报错

Java中将pdf文件转成image后,pdf文件删除失败,怎么回事? 400 报错 private  void pdfToJPG(String inputFile)
throws IOException {


// load a pdf from a byte buffer
File file = new File(inputFile);


RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,
channel.size());
PDFFile pdffile = new PDFFile(buf);
int totalpage =pdffile.getNumPages();
for (int i = 1; i <= totalpage; i++) {
if (i == 1) {
// draw the first page to an image
// 以图片的形式来描绘首页
PDFPage page = pdffile.getPage(i);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());

// generate the image
// 生成图片
Image img = page.getImage(rect.width, rect.height, // width &
// height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage tag = new BufferedImage(rect.width, rect.height,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img.getScaledInstance(rect.width, rect.height,  Image.SCALE_SMOOTH), 0, 0, rect.width, rect.height,
null);

FileOutputStream out = new FileOutputStream( imagePath+"\"+fileName.substring(fileName.lastIndexOf("/")+1)
+ ".jpg"); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
// 关闭输出流
out.close();
break;
}
}
buf.clear();
channel.close();
raf.close();
file.delete();

}
public void destroy(){
if(this.pdfFile.exists()){
System.out.println(this.pdfFile.delete());
}

}

生成图片后执行destroy,打印FALSE,pdf删除失败,求高手指点

展开
收起
爱吃鱼的程序员 2020-06-01 13:28:41 604 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    注意你这句代码:

    ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,channel.size());
    这句代码通道建立了map映射,你在file.delete();这句代码的前面,仅仅把buffer 给 clear了

    Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.

    此时并没有解除映射,所以你在删除之前还要把映射解除:
    public static <T> void unmap(final Object buffer) {
        AccessController.doPrivileged(new PrivilegedAction<T>(){
            @Override
    	public T run() {				
    	    try {
    		Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
    		getCleanerMethod.setAccessible(true);
    		sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
    		cleaner.clean();
    	    } catch(Exception e) {
    		    e.printStackTrace();
    	    }				
    	    return null;
    	}			
        });
    }
    最终是:

    unmap(buf);

    file.delete()

    这样就可以删除了,你试试。

    ######太谢谢了,加上这个就可以了,非常感谢
    2020-06-01 13:28:43
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载