Dom4j SAXReader读取xml异常时占用文件,导致不能移动文件

原文地址:   http://blog.csdn.net/ablipan/article/details/8198692


使用SAXReader的read(File file)方法时,如果xml文件异常会导致文件被服务器占用不能移动文件,建议不使用read(File file)方法而使用read(FileInputStream fis)等流的方式读取文件,异常时关闭流,这样就不会造成流未关闭,文件被锁的现象了。(在服务器中运行时会锁住文件,main方法却不会)。


1、以下方式xml文件异常时会导致文件被锁

[java]  view plain copy print ?
  1.                    Document document = null;  
  2. File file = new File(xmlFilePath);  
  3. SAXReader saxReader = new SAXReader();  
  4. try  
  5. {  
  6.     document = saxReader.read(file);  
  7. catch (DocumentException e)  
  8. {  
  9.     logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);  
  10. }  


2、以下方式xml文件异常时不会锁文件(也可以使用其他的流来读文件)

[java]  view plain copy print ?
  1.                 Document document = null;  
  2. FileInputStream fis = null;  
  3. try  
  4. {  
  5.     fis = new FileInputStream(xmlFilePath);  
  6.     SAXReader reader = new SAXReader();  
  7.     document = reader.read(fis);  
  8. }   
  9. catch (Exception e)  
  10. {  
  11.     logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);  
  12. }   
  13. finally  
  14. {  
  15.     if(fis != null)  
  16.     {  
  17.         try  
  18.         {  
  19.             fis.close();  
  20.         } catch (IOException e)  
  21.         {  
  22.             logger.error("将文件[" + xmlFilePath + "]转换成Document,输入流关闭异常", e);  
  23.         }  
  24.     }  
  25. }  


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值