Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading bytes from compressed PDF file in Java

When I try to read bytes from a normal PDF file into a byte array using "read" function in Java, the byte array is loaded correctly with size same as that of original PDF file.

Path file_path = Paths.get("D:\\Zip Test Client", "vadClient1.pdf");
    byte[] ByteArray= Files.readAllBytes(file_path);
    FileOutputStream fos = new FileOutputStream(new File("E:\\newFinalPDF.pdf"));

But when I read bytes from the same PDF file located inside a zipped folder, the read function reads only 8843 bytes (original size is 194471) and rest all are 0.

zipFile = new ZipFile(new File("D:\\Zip test Server\\ZipTestFolderOnServer.zip"));
        long count = zipFile.size();
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while(entries.hasMoreElements()){

            System.out.println("New File starting");
            ZipEntry zipEntry = entries.nextElement();
            System.out.println(zipEntry.getName());
            InputStream fis =  zipFile.getInputStream(zipEntry); 
            byte[] fileToBytes = new byte[(int)zipEntry.getSize()];


            FileOutputStream fos = new FileOutputStream(new File("E:\\ContentZipped_"   + zipEntry.getName()));
            fis.read(fileToBytes);
            fos.write(fileToBytes);
            fis.close();
            Thread.sleep(1000);
            --count;
        }

What is the explanation to this behavior?

EDIT 1:- I am not looking for third party integrations such as Tika or POI.

like image 916
blackstar Avatar asked Sep 10 '26 14:09

blackstar


1 Answers

Let's make it less error prone (and less memory consuming) by simplifying the code, use this to copy the content of your zip entry:

try (InputStream fis =  zipFile.getInputStream(zipEntry)) {
    Files.copy(fis, Paths.get("E:\\ContentZipped_"   + zipEntry.getName()));
}
like image 159
Nicolas Filotto Avatar answered Sep 13 '26 07:09

Nicolas Filotto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!