使用文件参数关闭StreamSource

时间:2017-08-24 17:07:19

标签: file

我想关闭StreamSource,我试过这段代码

   try {
     sc = new StreamSource(xmlFile);
     // check stuff
   } finally {
   sc.getInputStream().close();
    }

但是sc.getInputStream()返回null

我的代码:

    File file = new File("C:\Users\Lenovo\file.xml");
    StreamSource sourceXml = new StreamSource(file);

验证后我想关闭sourceXml

 try {
    File file = new File("C:\Users\Lenovo\file.xml");
    StreamSource sourceXml = new StreamSource(file);
    //validaion
   }catch(.....){
    }
   finally {
   sourceXml.getInputStream().close();
    }

我得到了nullPointerException

1 个答案:

答案 0 :(得分:0)

假设使用Java 7,您可以使用自动资源管理关闭InputStream,而不是在try-finally中关闭它。例如:

try {
    File file = new File("C:\\Users\\Lenovo\\file.xml");
    try (InputStream xmlStream = new StreamSource(file).getInputStream()) {
        //Validation
    }
} catch (Exception e) {
    //catch errors
}

以下是有关此主题的更多信息:http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html