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();
}
}
// ...关闭输出流,并删除临时文件
}
问题解决!