原文地址: http://blog.youkuaiyun.com/ablipan/article/details/8198692
使用SAXReader的read(File file)方法时,如果xml文件异常会导致文件被服务器占用不能移动文件,建议不使用read(File file)方法而使用read(FileInputStream fis)等流的方式读取文件,异常时关闭流,这样就不会造成流未关闭,文件被锁的现象了。(在服务器中运行时会锁住文件,main方法却不会)。
1、以下方式xml文件异常时会导致文件被锁
- 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文件异常时不会锁文件(也可以使用其他的流来读文件)
- 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处理XML文件时可能遇到的问题,特别是当XML文件存在错误时如何避免文件被锁定的情况。推荐使用FileInputStream替代File作为输入源,并确保在异常情况下能够正确关闭流。
174

被折叠的 条评论
为什么被折叠?



