在java中流关闭exception

请看看我做了什么

private InputSource getContent(String fName) throws SAXException, IOException, ServiceException { // Some code here if(currentNodeRef != null) { ContentReader reader = contentService.getReader(currentNodeRef,ContentModel.PROP_CONTENT); InputStream inputStream = null; try { inputStream = new BufferedInputStream(reader.getContentInputStream(),16384); return new InputSource(inputStream); } finally { if(inputStream!=null) try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return new InputSource(); } 

在我的parseDocument方法中,我调用了上面的方法。

 parseDocRoot(getContent(fName),path); 

在parseDocRoot中

 public void parseDocRoot (InputSource ins, String path) throws SAXException, IOException, ParserConfigurationException, ServiceException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream(new byte[0])); } }); Document doc = builder.parse(ins); NodeList list = doc.getChildNodes(); parseDocument(list,path); } 

我收到一个错误说流不关闭,在调试上面的代码时,我发现错误就行了

 Document doc = builder.parse(ins); 

请帮我找到解决方案。

我认为错误是流关闭。 原因是你有一个finally块:

  try { inputStream = new BufferedInputStream(reader.getContentInputStream(),16384); return new InputSource(inputStream); } finally { if(inputStream!=null) try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 

关闭 finally块中的流。 此代码在从方法返回之前立即执行。 重要的是,直到方法返回并由parse方法处理之后才会使用 InputStream。

您应该将finally块放在整个代码块周围 – 在实际完成时关闭流。 最简单的方法是内联你的getContent方法并在调用parse之后放入finally块。 在你这样做之后,你或许可以找到一种方法来封装那个逻辑,但是它会有点棘手,因为你必须保持对InputStream的处理,直到你完成解析为止你可以关闭它。

另一个更简单的选择是通过简单地移动parseDocRoot(getContent(fName),path);使getContent返回一个Document parseDocRoot(getContent(fName),path); 在那个方法里面。