本文介紹了DocumentBuilder.parse是否關閉InputStream的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
對于類似以下內容的代碼:
InputStream is = new FileInputstream("test.xml");
Document doc = DocumentBuilder.parser(is);
我的問題是,我是否需要手動關閉流(調用is.lose())。DocumentBuilder是否為我關閉InputStream?
推薦答案
使用以下測試代碼查看輸入流是否關閉,您可以看到哪行代碼關閉了流。
public class DocumentBuilderTest {
public static void main(String[] args) {
try {
InputStream is = new MyInputStream("project.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
documentBuilder.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
}
static class MyInputStream extends FileInputStream {
public MyInputStream(String filename) throws FileNotFoundException {
super(filename);
}
@Override
public void close() throws IOException {
// here we log when the stream is close.
System.out.println("file input stream closed.");
Exception e = new Exception();
e.printStackTrace();
super.close();
}
}
}
傳遞給DocumentBuilder的輸入流是否關閉取決于DOMParser實現。在我的環境中,文件輸入流是關閉的,請參見下面的堆棧跟蹤:
at DocumentBuilderTest$MyInputStream.close(DocumentBuilderTest.java:37)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager$RewindableInputStream.close(XMLEntityManager.java:3047)
at com.sun.org.apache.xerces.internal.impl.io.UTF8Reader.close(UTF8Reader.java:661)
at com.sun.xml.internal.stream.Entity$ScannedEntity.close(Entity.java:441)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.endEntity(XMLEntityManager.java:1406)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.load(XMLEntityScanner.java:1763)
at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.skipSpaces(XMLEntityScanner.java:1543)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$TrailingMiscDriver.next(XMLDocumentScannerImpl.java:1400)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:235)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at DocumentBuilderTest.main(DocumentBuilderTest.java:22)
因此您不能在此特定示例中手動關閉流。但是,當您確定不再使用輸入流時,關閉輸入流始終是個好主意。在您的情況下,一旦解析了文檔,就不再需要輸入流,因此可以安全地關閉流,我建議您這樣做。
這篇關于DocumentBuilder.parse是否關閉InputStream的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,