DocumentBuilder.parse是否关闭InputStream

2022-04-09 00:00:00 xml java 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)

因此您不能在此特定示例中手动关闭流。但是,当您确定不再使用输入流时,关闭输入流始终是个好主意。在您的情况下,一旦解析了文档,就不再需要输入流,因此可以安全地关闭流,我建议您这样做。

相关文章