我想编写一个方法,从一个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();
}
}有问题的部分是"//读取流“。我有一个可行的解决方案,它包括创建一个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 sc = new Scanner(zis);
while (sc.hasNextLine())
{
System.out.println(sc.nextLine());
}但是..。我目前使用的解析器(jdom2,但我也尝试过使用javax.xml.parsers.DocumentBuilderFactory)在解析数据:/之后关闭了流。所以我无法获得下一个条目并继续。
因此,最后的问题是:
谢谢。
发布于 2013-11-16 16:50:19
您可以包装ZipInputStream并拦截对close()的调用。
发布于 2013-12-11 07:52:52
提姆解决方案的一个小改进:在close()之前必须调用allowToBeClosed()的问题是,当处理异常时,它会使关闭ZipInputStream变得非常困难,并且会破坏Java7的试用式资源语句。
我建议创建包装类,如下所示:
public class UncloseableInputStream extends InputStream {
private final InputStream input;
public UncloseableInputStream(InputStream input) {
this.input = input;
}
@Override
public void close() throws IOException {} // do not close the wrapped stream
@Override
public int read() throws IOException {
return input.read();
}
// delegate all other InputStream methods as with read above
}这样就可以安全地使用如下:
try (ZipInputStream zipIn = new ZipInputStream(...))
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
ZipEntry entry;
while (null != (entry = zipIn.getNextEntry()))
{
if ("file.xml".equals(entry.getName())
{
Document doc = db.parse(new UncloseableInputStream(zipIn));
}
}
}发布于 2013-11-16 17:01:10
由于使用了半位,我最终得到了自己的ZipInputStream类,它覆盖了close方法:
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipInputStream;
public class CustomZipInputStream extends ZipInputStream {
private boolean _canBeClosed = false;
public CustomZipInputStream(InputStream is) {
super(is);
}
@Override
public void close() throws IOException {
if(_canBeClosed) super.close();
}
public void allowToBeClosed() { _canBeClosed = true; }
}https://stackoverflow.com/questions/20020982
复制相似问题