
使用 iText 处理 PDF 时,若在复制并修改原始 PDF 后无法删除原文件,通常是因为未显式关闭 PdfReader 关联的底层输入流,导致操作系统仍将其视为“被占用”。
使用 itext 处理 pdf 时,若在复制并修改原始 pdf 后无法删除原文件,通常是因为未显式关闭 `pdfreader` 关联的底层输入流,导致操作系统仍将其视为“被占用”。
在你提供的代码中,虽然调用了 reader.close(),但该方法仅释放 iText 内部资源,并不自动关闭其背后持有的 FileInputStream(如果由用户传入)。而你的 PdfReader 是通过 new PdfReader(new FileInputStream(originalFile)) 构造的——这意味着你手动创建了 FileInputStream,但从未调用其 close() 方法,造成文件句柄泄漏。
✅ 正确做法是:显式管理输入流生命周期,推荐使用 try-with-resources 确保安全释放:
// 替换原代码中这一行:
// PdfReader reader = new PdfReader(new FileInputStream(originalFile));
// 改为:
PdfReader reader;
try (FileInputStream fis = new FileInputStream(originalFile)) {
reader = new PdfReader(fis);
// 后续处理页数、导入等逻辑保持不变
for (int i = 0; i <p>⚠️ 注意事项:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5450" title="协同养育操作系统"><img
src="https://img.php.cn/upload/skill/000/000/081/179050145216387.jpg" alt="协同养育操作系统" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5450" title="协同养育操作系统" class="overflowclass">协同养育操作系统</a>
<p class="overflowclass">协同养育操作系统(Co-Parenting OS)— 离异家庭专业协同养育支持系统。12模块覆盖接送管理、成长记忆库、孩子观察站、亲子关系粘合剂、共同挑战中心、情绪冲突观察、父母成长、成长档案馆、成长阶段引擎、风险预警、驾驶舱、被恶意攻击急救包。当用户涉及离异家庭育儿、协同养育、抚养探视、接送安排、孩子成长记录、亲子关系、离异冲突、被恶意攻击、前任矛盾等话题时触发。</p>
</div>
<a rel="nofollow" href="/xiazai/skill5450" title="协同养育操作系统" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
-
duplicateDocument.newPage()在最后一页后无需再调用,否则会生成空白页;判断条件应为i ; -
writer.flush()和writer.close()已隐含在duplicateDocument.close()中,无需重复调用(除非特殊场景),冗余调用可能引发异常; -
outputStream.flush()和outputStream.close()同样可由 try-with-resources 管理更安全(建议将BufferedOutputStream也纳入资源声明); - Windows 系统对文件锁尤为敏感,即使 JVM 退出前未释放流,也可能导致
java.nio.file.FileSystemException: ... The process cannot access the file because it is being used by another process。
? 总结:iText 的 PdfReader 不会自动关闭外部传入的 InputStream。凡是通过 new FileInputStream(...) 创建的流,必须显式关闭(优先用 try-with-resources)。只有彻底释放所有相关资源(输入流、输出流、reader、document、writer),才能确保原始 PDF 文件可被正常删除。










