public List<Element> readXml(String filePath){
List<Element> list = null;
FileInputStream fis = null;
FileChannel fc = null;
FileLock fl = null;
try{
// File file = new File(filePath);
fis = new FileInputStream(filePath);
fc = fis.getChannel();
fl = fc.tryLock(0,Long.MAX_VALUE,true);
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(fis);
Element rootElement = document.getRootElement();
list = rootElement.elements();

}catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(null != fl){
fl.release();
fl.close();
}
if(null != fc&&fc.isOpen()){
fc.close();
}
if(null != fis){
fis.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
return list;
}
saxReader用File方式读取XML后XML会一直被占用,后来改用FileInputStream,还是不行,最后就自己给文件加锁,读取完后,把锁释放,还是不行,文件一直被占用,求大神解决!javasaxReaderj2EEjavaWEBXML

解决方案 »

  1.   

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

  2.   

    我在上面也用了FileInputStream,FileInputStream 对服务器端是无用的,我现在就是服务器端啊!
      

  3.   

    问题解决/**
     * 读取XML
     * @param filePath XML文件路径
     * @return XML节点集
     */
    @SuppressWarnings("unchecked")
    public List<Element> readXml(String filePath){
    List<Element> list = null;
    FileInputStream fis = null;
    try{
    // File file = new File(filePath);
    fis = new FileInputStream(filePath);
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(fis);
    Element rootElement = document.getRootElement();
    list = rootElement.elements();
    }catch (Exception e) {
    e.printStackTrace();
    }finally{
    try{
    if(null != fis){
    fis.close();
    System.gc();
    Thread.sleep(5000);
    }
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    return list;
    }