为什么我得到java.io.IOException:stream是关闭异常?

时间:2018-06-03 08:21:31

标签: java xml inputstream ioexception

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

  1. 验证XML的输入流
  2. 将Inputstream转换为XML以进行处理
  3. 我在客户端类中的验证代码如下

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

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

1 个答案:

答案 0 :(得分:0)

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