有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

xml为什么我要使用java。伊奥。IOException:流已关闭异常?

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

  1. 验证XML的Inputstream
  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;
}

}

输入流的处理过程如下

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抛出解析错误。因此,在验证部分,流可能会在某个地方关闭,但我不确定在哪里

谢谢你的阅读。谢谢你的帮助


共 (0) 个答案