首页 > 解决方案 > 为什么我收到 java.io.IOException: stream is closed 异常?

问题描述

从我的 java 客户端,我试图从返回 XML 的 python 服务器获取数据。我的步骤是:

  1. 验证 XML 的输入流
  2. 将 Inputstream 转换为 XML 进行处理

我在客户端类中的验证代码如下

public static boolean isValidXML(InputStream xmlInputStream) {
    try {
        Source xmlFile = new StreamSource(xmlInputStream);
        URL schemaFile = new URL("https://www.w3.org/2001/XMLSchema.xsd");
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaFile);
        Validator validator = schema.newValidator();

        validator.setErrorHandler(new ErrorHandler() {

                // all the overridden methods 
        });

        validator.validate(xmlFile);

    } catch (SAXException ex) {
        System.out.println(ex.getMessage());
        return false;

    } catch (IOException e) {
        System.out.println(e.getMessage());
        return false;
    }
    return true;
}

}

InputStream 的处理是这样的

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
if (MyClient.isValidXML(con.getInputStream())) {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String inline = "";
            while ((inline = inputReader.readLine()) != null) {
                sb.append(inline);
            }

            SAXBuilder builder = new SAXBuilder();

            Document document = (Document) builder.build(new 
            ByteArrayInputStream(sb.toString().getBytes()));
}

在执行时,while 循环语句 -while ((inline = inputReader.readLine()) != null)抛出流是关闭异常。

如果我删除了验证部分,那么处理会按预期进行,当然除了一些格式错误的 XML 会引发解析错误。所以可能流在验证部分的某个地方被关闭了,但我不确定在哪里。

谢谢阅读。我感谢您的帮助。

标签: javaxmlinputstreamioexception

解决方案


发生这种情况是因为您通过验证已用尽并关闭了输入流。你既养狗又叫自己。如果在输入无效时解析已经抛出异常,则根本不需要验证步骤。所以删除它。


推荐阅读