我希望编写一个方法,从单个InputStream中读取ZIP中的多个XML文件。
该方法将打开一个ZipInputStream,在每个xml文件上获取相应的InputStream,并将其传递给我的XML解析器。以下是该方法的基本结构:
private void readZip(InputStream is) throws IOException {
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
if (entry.getName().endsWith(".xml")) {
// READ THE STREAM
}
entry = zis.getNextEntry();
}
}
问题出在 "// READ THE STREAM" 这段代码。我有一个可行的解决方案,它创建了一个ByteArrayInputStream,并将其提供给我的解析器。但是对于大文件,它使用缓存,会导致 OutOfMemoryError 错误。如果有人还感兴趣,以下是代码:
int count;
byte buffer[] = new byte[2048];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((count = zis.read(buffer)) != -1) { out.write(buffer, 0, count); }
InputStream is = new ByteArrayInputStream(out.toByteArray());
理想的解决方案是将原始的ZipInputStream提供给解析器。这应该可行,因为如果我只使用Scanner打印条目内容,则可以工作:
Scanner sc = new Scanner(zis);
while (sc.hasNextLine())
{
System.out.println(sc.nextLine());
}
但是...我目前使用的解析器(jdom2,但我也尝试过javax.xml.parsers.DocumentBuilderFactory)在解析数据后会关闭流:/。因此,我无法获取下一个条目并继续。
所以最后的问题是:
- 有人知道一种DOM解析器不会关闭其流吗?
- 还有其他方法可以从ZipEntry中获得InputStream吗?
谢谢。