You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iText关闭PDF文档后删除文件时抛出进程占用错误

解决iTextPDF读取后文件被占用无法删除的问题

问题原因

你这段代码里,通过FileInputStream初始化PdfReader后,仅关闭了PdfDocument,但底层的FileInputStream并未被正确关闭,导致文件句柄被占用,执行删除操作时就会出现「源文件正被其他进程占用,无法删除」的错误。

解决方案

方案1:直接用文件路径初始化PdfReader(推荐)

让iText自动管理文件流的打开与关闭,无需手动处理FileInputStream:

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class PDFSplitter {
    private static final String INPUT_FILE = "C:\\test.pdf";

    public static void main(String args[]) throws IOException {
        PdfReader pdfReader = new PdfReader(INPUT_FILE);
        PdfDocument pdfDocument = new PdfDocument(pdfReader);
        pdfDocument.close();    
        Files.delete(Paths.get(INPUT_FILE));
    }
}

方案2:手动管理FileInputStream的关闭

如果必须使用FileInputStream,可以通过try-with-resources语法自动关闭所有资源(该语法会自动关闭实现AutoCloseable接口的对象):

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class PDFSplitter {
    private static final String INPUT_FILE = "C:\\test.pdf";

    public static void main(String args[]) throws IOException {
        try (FileInputStream fis = new FileInputStream(INPUT_FILE);
             PdfReader pdfReader = new PdfReader(fis);
             PdfDocument pdfDocument = new PdfDocument(pdfReader)) {
            // 在这里添加PDF处理逻辑
        }
        Files.delete(Paths.get(INPUT_FILE));
    }
}

说明

两种方案的核心都是确保所有与文件关联的流和资源都被完全关闭,释放文件句柄后,就能正常执行删除操作。

内容的提问来源于stack exchange,提问作者nonlinear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:47:35