3

我有一个 docx 文件的 inputStream,我需要获取位于 docx 内的 document.xml。

我正在使用 ZipInputStream 来读取我的流,我的代码类似于

    ZipInputStream docXFile = new ZipInputStream(fileName);
    ZipEntry zipEntry;
    while ((zipEntry = docXFile.getNextEntry()) != null) {
        if(zipEntry.getName().equals("word/document.xml"))
        {
            System.out.println(" --> zip Entry is "+zipEntry.getName());
        } 
    }

如您所见,zipEntry.getName 的输出有时会以“word/document.xml”的形式出现。我需要将此 document.xml 作为流传递,与 ZipFile 方法不同,您可以在调用 .getInputStream 时轻松传递它,我想知道如何执行此 docXFile?

提前致谢, 米纳克希

@Update:我找到了这个解决方案的输出:

       ZipInputStream docXFile = new ZipInputStream(fileName);
    ZipEntry zipEntry;
    OutputStream out;

    while ((zipEntry = docXFile.getNextEntry()) != null) {
        if(zipEntry.toString().equals("word/document.xml"))
        {
            System.out.println(" --> zip Entry is "+zipEntry.getName());
            byte[] buffer = new byte[1024 * 4];
            long count = 0;
            int n = 0;
            long size = zipEntry.getSize();
            out = System.out;

            while (-1 != (n = docXFile.read(buffer)) && count < size) {
                out.write(buffer, 0, n);
               count += n;
            }
        }
    }

我想知道是否有一些基本的 API 可以将此输出流转换为输入流?

4

1 回答 1

2

Something like this should work (not tested):

ZipFile zip = new ZipFile(filename)
Enumeration entries = zip.entries();
while ( entries.hasMoreElements()) {
   ZipEntry entry = (ZipEntry)entries.nextElement();

   if ( !entry.getName().equals("word/document.xml")) continue;

   InputStream in = zip.getInputStream(entry);
   handleWordDocument(in);
}

Further you might take a look at some other zip library besides the built in one. AFAIK the build-in one does not support all modern compression levels / encryption and other stuff.

于 2010-05-06T09:26:41.090 回答