Getting document.xml from a docx file using ZipInputStream

I have an inputStream of a docx file and I need to get the document.xml document that is inside the docx.

I am using ZipInputStream to read my stream, and my code is something like

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

As you can see. The result for zipEntry.getName at some point appears as "word / document.xml". I need to pass this document.xml as a stream and unlike the ZipFile method, where you can easily pass this when calling .getInputStream, I wonder how can I do this docXFile?

Thanks in advance, Meenakshi

@Update: I found a way out for this solution:

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

I am wondering if there is some basic API to convert this output stream to input stream?

+3
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 / .

+2

Source: https://habr.com/ru/post/1744304/


All Articles