Dom4j SAXReader读取xml异常时占用文件,导致不能移动文件
2015-06-24 16:27
776 查看
原文地址: http://blog.csdn.net/ablipan/article/details/8198692
使用SAXReader的read(File file)方法时,如果xml文件异常会导致文件被服务器占用不能移动文件,建议不使用read(File file)方法而使用read(FileInputStream fis)等流的方式读取文件,异常时关闭流,这样就不会造成流未关闭,文件被锁的现象了。(在服务器中运行时会锁住文件,main方法却不会)。
1、以下方式xml文件异常时会导致文件被锁
[java] view
plaincopyprint?
Document document = null;
File file = new File(xmlFilePath);
SAXReader saxReader = new SAXReader();
try
{
document = saxReader.read(file);
} catch (DocumentException e)
{
logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);
}
2、以下方式xml文件异常时不会锁文件(也可以使用其他的流来读文件)
[java] view
plaincopyprint?
Document document = null;
FileInputStream fis = null;
try
{
fis = new FileInputStream(xmlFilePath);
SAXReader reader = new SAXReader();
document = reader.read(fis);
}
catch (Exception e)
{
logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);
}
finally
{
if(fis != null)
{
try
{
fis.close();
} catch (IOException e)
{
logger.error("将文件[" + xmlFilePath + "]转换成Document,输入流关闭异常", e);
}
}
}
使用SAXReader的read(File file)方法时,如果xml文件异常会导致文件被服务器占用不能移动文件,建议不使用read(File file)方法而使用read(FileInputStream fis)等流的方式读取文件,异常时关闭流,这样就不会造成流未关闭,文件被锁的现象了。(在服务器中运行时会锁住文件,main方法却不会)。
1、以下方式xml文件异常时会导致文件被锁
[java] view
plaincopyprint?
Document document = null;
File file = new File(xmlFilePath);
SAXReader saxReader = new SAXReader();
try
{
document = saxReader.read(file);
} catch (DocumentException e)
{
logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);
}
2、以下方式xml文件异常时不会锁文件(也可以使用其他的流来读文件)
[java] view
plaincopyprint?
Document document = null;
FileInputStream fis = null;
try
{
fis = new FileInputStream(xmlFilePath);
SAXReader reader = new SAXReader();
document = reader.read(fis);
}
catch (Exception e)
{
logger.error("将文件[" + xmlFilePath + "]转换成Document异常", e);
}
finally
{
if(fis != null)
{
try
{
fis.close();
} catch (IOException e)
{
logger.error("将文件[" + xmlFilePath + "]转换成Document,输入流关闭异常", e);
}
}
}
相关文章推荐
- 程序语言 -- Python编码规范
- nodejs怎么同步从一个数据库查询函数中返回一个值
- 在非主线程中创建窗口
- 去除混叠干扰
- 【读书笔记】Linux高性能服务器编程(第一篇 第四章)
- Effective minidump
- WinForm入门
- printf的另类用法
- 字节位操作(位域的应用)
- AngularJS tips-2 初始篇
- ubuntu install xsltproc docbook-xsl docbook-xml
- Socket 学习(三).5 UDP 的弱点
- aix下java程序运行问题
- linux问题
- jQuery开发之Ajax
- LR进行多分类theano代码分析
- win8.1不能正常关机怎么办?win8.1无法关机的解决办法
- 学习ASP.NET MVC5框架揭秘笔记-ASP.NET MVC路由(五)
- VI使用技巧
- libevent signal 信号事件