2017-08-24 25 views
0

我想結束StreamSource的,我想這碼與文件參數關閉的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

回答

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

+0

謝謝你,但文件的類型必須是來源 因爲驗證功能有源 – Alex

+0

來源sourceXml =新的StreamSource的輸入(新文件(XMLFILE)); //驗證 //關閉 我不知道如何關閉sourceXml – Alex