使用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);
}
}
}