java中的流关闭异常
请看看我做了什么java中的流关闭异常,java,exception,stream,Java,Exception,Stream,请看看我做了什么 private InputSource getContent(String fName) throws SAXException, IOException, ServiceException { // Some code here if(currentNodeRef != null) { ContentReader reader = contentService.getReader(currentNodeR
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
返回一个文档
代码>在该方法中。第一个答案很可能是正确的,但通常最好提供完整的堆栈跟踪,而不是错误描述;这会让事情更简单,避免混乱。谢谢柯克。我已经试过了,并且成功了。谢谢你的回答。这个答案是正确的,但是您构建代码的方式可能并不理想,因为我猜您现在根本没有关闭流。我建议不要使用单独的方法返回InputSource。我认为尝试用同样的方法打开和关闭流是一个很好的实践。(显然,您可以调用其他方法来处理流)。@MeBigFatGuy,我相信这就是我的建议。特别是我的最后一个建议,简单地返回一个文档
——这个想法是让getContent
负责打开和关闭流。