i2i*_*eya 1 java exception stream
请看看我做了什么
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();
}
Run Code Online (Sandbox Code Playgroud)
在我的parseDocument方法中,我调用了上面的方法.
parseDocRoot(getContent(fName),path);
Run Code Online (Sandbox Code Playgroud)
在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);
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说流不关闭,在调试上面的代码时,我发现错误就行了
Document doc = builder.parse(ins);
Run Code Online (Sandbox Code Playgroud)
请帮我找到解决方案.
我相信错误是流已关闭.原因是你有一个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();
}
}
Run Code Online (Sandbox Code Playgroud)
您关闭 finally块中的流.此代码在从方法返回之前立即执行.重要的是,直到方法返回并由方法处理之后才会使用 InputStream parse.
您应该将finally块放在整个代码块周围 - 在实际完成时关闭流.最简单的方法是内联你的getContent方法并在调用后放入finally块parse.在你这样做之后,你或许可以找到一种方法来封装那个逻辑,但它会有点棘手,因为你必须保持一个InputStream句柄,直到你完成解析,这样你就可以关闭它.
另一个更简单的选择是通过简单地在该方法内移动来getContent返回a .DocumentparseDocRoot(getContent(fName),path);
| 归档时间: |
|
| 查看次数: |
25656 次 |
| 最近记录: |