java代码删除文件__发现无法删除
File file = new File(filePath);
if (file.exists() && file.isFile()) {
boolean flag = file.delete();
}
经过对比检查发现 flag 为 false 并没有删除__
通过界面删除,报错如图__被另一个进程占用
解决方案一:
强制回收资源,然后删除
public static void delFile(String filePath) {
if (StringUtils.isNotBlank(filePath)) {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
boolean flag = file.delete();
if (!flag) {
System.gc();//系统进行资源强制回收
boolean f = file.delete();
System.out.println(f);
}
}
}
}
方案二:
可能原因执之前对此文件的操作刘没有关闭,需要关闭流
public void createDoc(Map<String, Object> dataMap, String downloadType, String savePath) {
Writer out = null;
try {
//加载需要装填的模板
Template template = null;
//加载模板文件
configure.setClassForTemplateLoading(this.getClass(), "/com/sgcc/fsp/manage/web/templates");
//设置对象包装器
configure.setObjectWrapper(new DefaultObjectWrapper());
//设置异常处理器
configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
//定义Template对象,注意模板类型名字与downloadType要一致
template = configure.getTemplate(downloadType + ".xml");
//输出文档
File outFile = new File(savePath);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
template.process(dataMap, out);
outFile.delete();
} catch (Exception e) {
e.printStackTrace();
}finally {
//此处需要关闭流___关闭流后可以正常删除呢
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}