【问题标题】:Getting document.xml from a docx file using ZipInputStream使用 ZipInputStream 从 docx 文件中获取 document.xml
【发布时间】:2010-05-06 08:44:30
【问题描述】:

我有一个 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?

提前致谢, 米纳克希

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

       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 可以将此输出流转换为输入流?

【问题讨论】:

    标签: java xml docx zipinputstream


    【解决方案1】:

    这样的东西应该可以工作(未经测试):

    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);
    }
    

    此外,您还可以查看除内置压缩库之外的其他 zip 库。 AFAIK 内置的不支持所有现代压缩级别/加密和其他东西。

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多