java - 为什么我收到 java.io.IOException: stream is closed 异常?
问题描述
从我的 java 客户端,我试图从返回 XML 的 python 服务器获取数据。我的步骤是:
- 验证 XML 的输入流
- 将 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 会引发解析错误。所以可能流在验证部分的某个地方被关闭了,但我不确定在哪里。
谢谢阅读。我感谢您的帮助。
解决方案
发生这种情况是因为您通过验证已用尽并关闭了输入流。你既养狗又叫自己。如果在输入无效时解析已经抛出异常,则根本不需要验证步骤。所以删除它。
推荐阅读
- jquery - Angular CLI 7.1.4 中未加载外部 JS 文件
- php - Memcached PHP 会话错误:session_start():读取会话数据失败
- stata - 生成新变量时忽略缺失值
- c# - “System.DateTime”不包含“Value”的定义,也没有接受第一个参数的扩展方法“Value”
- php - Mysqli stmt 绑定并执行失败
- python - 重塑 np 数组以进行深度学习
- python - 在 Pygame 1.9.4 中使用 move_ip
- javascript - 垃圾邮件注入链接的位置
- apache-flink - 使用 Kafka Connect 和 Flink 的实时流数据管道
- php - 在多维数组中搜索多个特定值