开发者社区> 问答> 正文

java 能否在catch中进行文件删除:报错

如下代码所示,我希望分析test文件夹下的xml,现在又5个xml文件,执行下面代码后,结果如下。由于文件ddmk_weibo_fenxishi_list_16944905_3098730807.xml,不能正确读取,我希望进行删除。在catch里执行filelist[i].delete(),但是执行后该文件未被删除。

请问该怎么解决呢?

package myproject;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class xmlValidate {
	public static void main(String[] args) {
	
			String directory="C:/Users/long/DataScraperWorks/test";
    		String fileSuffix = ".xml"; 
    		File file = new File(directory);
    		File[] filelist = file.listFiles();
    		for(int i=0;i<filelist.length;i++){    			
    			if(filelist[i].getName().lastIndexOf(fileSuffix)!=-1){
    				String filename = filelist[i].getName();
    	            SAXReader reader = new SAXReader();
    	            try {
						Document document = reader.read(directory+"/"+filename);
	    	            System.out.println(filelist[i].getName()+" Load success!");
	    	            //filelist[i].delete();
					} catch (DocumentException e) {
						// TODO Auto-generated catch block
						System.out.println(e.getMessage());
						System.out.println(filelist[i].getName()+" load fail");
						filelist[i].delete();
					}
    			}
    		}

	
	
	}
}
输出结果:
ddmk_weibo_fenxishi_list_16944899_3106567492.xml Load success!
ddmk_weibo_fenxishi_list_16944903_3098714823.xml Load success!
ddmk_weibo_fenxishi_list_16944904_3098704145.xml Load success!
Error on line 690 of document file:///C:/Users/long/DataScraperWorks/test/ddmk_weibo_fenxishi_list_16944905_3098730807.xml : An invalid XML character (Unicode: 0xc) was found in the element content of the document. Nested exception: An invalid XML character (Unicode: 0xc) was found in the element content of the document.
ddmk_weibo_fenxishi_list_16944905_3098730807.xml load fail

展开
收起
kun坤 2020-06-07 22:02:10 651 0
1 条回答
写回答
取消 提交回答
  • 试试 FileUtils.forceDelete(...) 方法, commons-io 项目里的
    ######谢谢。我去试试。 主要我想在对文件进行判断后,删除抛出异常的文件!希望Commons-IO能解决这个删除问题!

    2020-06-07 22:02:15
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载