java 多个pdf文件合并,解决删除提示文件被占用

多个pdf文件合并成一个pdf文件。生成过后怎么也删除不了,估计有使用到的流没关闭,手动在文件夹中也无法删除,提示文件正在被占用,但是怎么查找代码也不知道哪里的流没关闭。

最后在循环中发现了new PdfReader(),每次循环都会生成一个新PdfReader对象,代码从循环中出来,但是对象并没有被销毁,即使从方法中走出来,也没有被销毁,导致文件无法删除,也不好使。

最终采用不以PdfReader去维护,以当前文件流来管理。

maven 依赖


<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.1</version>
</dependency>

 /**
     * 合并PDF文件
     * @param files 文件列表
     * @param output 输出的PDF文件
     * @throws AppException 合并的异常
     */
	 public static void mergeFileToPDF(List<File> files, File output) throws AppException  {
        Document document = null;
        PdfCopy copy = null;
        OutputStream os = null;
        try {
            os = new FileOutputStream(output);
            document = new Document();
            copy = new PdfCopy(document, os);
            document.open();
            for (File file : files) {
                if (!file.exists()) {
                    continue;
                }
                String fileName = file.getName();
                if (fileName.endsWith(".pdf")) {
                    PdfContentByte cb = copy.getDirectContent();
                    PdfOutline root = cb.getRootOutline();
                    new PdfOutline(root, new PdfDestination(PdfDestination.XYZ), fileName
                        .substring(0, fileName.lastIndexOf(".")));
                        // 不使用reader来维护文件,否则删除不掉文件,一直被占用
                    try (InputStream is = new FileInputStream(file)) {
                    	PdfReader reader = new PdfReader(is);
                    	int n = reader.getNumberOfPages();
                    	for (int j = 1; j <= n; j++) {
                    		document.newPage();
                    		PdfImportedPage page = copy.getImportedPage(reader, j);
                    		copy.addPage(page);
                    	}
                    } catch(Exception e) {
                    	logger.warn("error to close file : {}" + file.getCanonicalPath(), e);
                    }
                } else {
                    logger.warn("file may not be merged to pdf. name:" + file.getCanonicalPath());
                }
            }
        } catch (Exception e) {
            throw new AppException(e, ErrorCodes.class, ErrorCodes.IO_ACCESS_ERROR);
        } finally {
        	if (document != null) {
        		document.close();
        	}
        	if (copy != null) {
        		copy.close();
        	}
            if (os != null) {
                IOUtils.closeQuietly(os);
            }
        }
    }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值