POI读取Word文件之后,文件一直被占用,无法删除

本文探讨了在使用Apache POI库处理Word文档后,文件无法删除的问题,发现是由于XWPFDocument对象未正确关闭导致。通过找到合适的关闭方法和资源管理,解决了文件占用问题,确保文件能正常删除。
摘要由CSDN通过智能技术生成

POI读取Word文件之后,文件一直被占用,无法删除

使用poi读取word文件之后,文件就无法删除,一直正在使用
在这里插入图片描述
在操作完word文件之后也关闭了流,并在操作完成之后删除源文件,代码看着好像是没有问题

	FileOutputStream out = null;
	File tmpFile = null;
	try {
		String tmpFilePath = "tmp.docx";
		tmpFile = new File(tmpFilePath);
		XWPFDocument doc = new XWPFDocument(POIXMLDocument.openPackage(tmpFilePath));
		// 。。。读取并操作doc,并保存到新的word中
		String newFilePath= "newFile.docx";
		out = new FileOutputStream(newFilePath);
		File newFile= new File(newFilePath);
		if(!newFile.exists()){
			newFile.getParentFile().mkdirs();
			try {
				newFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		doc.write(out);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (out != null){
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (tmpFile != null && tmpFile.isFile()) {
			tmpFile.delete();
		}
	}

仔细一琢磨XWPFDocument对象没有关闭,相当于poi一直在占用着word文件,但是XWPFDocument又没有colse()方法

查看POIXMLDocument的API

在这里插入图片描述
POIXMLDocument类打开文件包之后确实有关闭的方法

	FileOutputStream out = null;
	File tmpFile = null;
	OPCPackage tmpPackage = null;
	try {
		// ...
		tmpPackage = POIXMLDocument.openPackage(tmpFilePath);
		XWPFDocument doc = new XWPFDocument(tmpPackage);
		// ...
	} catch (Exception e) {
		throw Exceptions.unchecked(e);
	} finally{
		if (tmpPackage != null){
			try {
				tmpPackage.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// ...关闭输出流,并删除临时文件
	}

问题解决!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值