xmleventreader关闭流

7uhlpewt  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(217)

我想流式处理一个包含几个非常大(~1gb)的xml文件的zip文件。我可以将每个zip文件中的数据读入一个缓冲区,并从中创建一个xmlstream—但是为了节省内存,我更喜欢动态处理数据。

@Test
public void zipStreamTest() throws IOException, XMLStreamException {
    FileInputStream fis = new FileInputStream("archive.zip");
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ei;

    while ((ei = zis.getNextEntry()) != null){      
        XMLEventReader xr = XMLInputFactory.newInstance().createXMLEventReader(zis);
        while (reader.hasNext()) {
            XMLEvent xe = xr.nextEvent();
            // do some xml event processing..
        }
        zis.closeEntry();
    }
    zis.close();
}

问题是:我得到了一个 java.io.IOException: Stream closed 执行时 zis.closeEntry(); . 当我删除那行时,同样的错误也会被抛出 zis.getNextEntry() 如果以前的条目仍然自动打开,则关闭它们。
似乎我的xml流读取器正在破坏xml文件末尾的流,因此无法处理zip的其余部分。
我是否有实现错误,或者我对流如何工作的概念是否不正确?
注意:为了使这个示例具有最小的可复制性,您只需要一个zip文件“archive.zip”,其中包含任何有效的xml文件(zip中没有子目录!)。然后可以使用junit运行代码段。

gab6jxml

gab6jxml1#

我建议使用 ZipFile 而不是 ZipInputStream ,正如亚历山德拉·杜德基纳在回答中所建议的那样。
但是,如果您正在处理数据流,例如下载,因此希望继续使用 ZipInputStream ,你应该把它包起来 CloseShieldInputStream 来自apache commons io1 getNextEntry() 回路:

while ((ei = zis.getNextEntry()) != null) {
    XMLEventReader xr = XMLInputFactory.newInstance().createXMLEventReader(new CloseShieldInputStream(zis));
    // Process XML here
    zis.closeEntry();
}

1) 或您选择的第三方库中的其他类似帮助程序类。

piztneat

piztneat2#

您可以尝试使用为每个条目打开单独的inputstream java.util.zip.ZipFile :

@Test
public void zipStreamTest() throws Exception {
        ZipFile zipFile = new ZipFile("archive.zip");
        Iterator<? extends ZipEntry> iterator = zipFile.entries().asIterator();
        while (iterator.hasNext()) {
            ZipEntry ze = iterator.next();
            try (InputStream zis = zipFile.getInputStream(ze)) {
                XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(zis);
                while (reader.hasNext()) {
                    XMLEvent xe = reader.nextEvent();
                    // do some xml event processing
                }
                reader.close();
            }
        }
    }

相关问题