PeJak
PeJak

Reputation: 5

ZipOutputStream - zipping files with wrong content

i can zipping files, but with wrong content ... for example - content in a.txt:


!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚„…†‡‰Š‹ŚŤŽŹ‘’“”•–—™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ`         

This is code for zipping file:

void zipping() throws FileNotFoundException, IOException {
        OutputStream os = new FileOutputStream("C:\\...\\newZip.zip");
        ZipOutputStream zos = new ZipOutputStream(os);

        File folder = new File("C:\\...\\A");

        for (final File fileEntry : folder.listFiles()) {
            //ZipEntry ze2 = new ZipEntry(fileEntry.getPath());
            //zos.putNextEntry(ze2);
            zos.putNextEntry(new ZipEntry(fileEntry.getName()));
            for (int i = 0; i < 10000; i++) {
                zos.write(i);
            }
        }
        zos.close();
    }

Where is bug? Thanks for help.

Upvotes: 0

Views: 497

Answers (2)

dARKpRINCE
dARKpRINCE

Reputation: 1568

You are writing bytes into the zip file, starting from 1 to 10000. So depending on the encoding used, the output you have shown is correct.

Maybe you should read from the files you want to zip. Below is the code modified from yours.

void zipping(File file) throws FileNotFoundException, IOException {
        OutputStream os = new FileOutputStream("C:\\...\\newZip.zip");
        ZipOutputStream zos = new ZipOutputStream(os);

        File folder = new File("C:\\...\\A");

        for (final File fileEntry : folder.listFiles()) {

            FileInputStream in = new FileInputStream(fileEntry);
            zos.putNextEntry(new ZipEntry(fileEntry.getName()));

            // buffer size
            byte[] b = new byte[1024];
            int count;

            // Read from file and write to zip file
            while ((count = in.read(b)) > 0) {
                zos.write(b, 0, count);
            }
        }    

        zos.close();
    }

Upvotes: 1

Ninad Pingale
Ninad Pingale

Reputation: 7069

Modify your code like this -

    OutputStream os = new FileOutputStream("C:\\newZip.zip");
    ZipOutputStream zos = new ZipOutputStream(os);

    File folder = new File("C:\\zipit");
    byte[] buffer = new byte[1024];
    for (final File fileEntry : folder.listFiles()) {
        zos.putNextEntry(new ZipEntry(fileEntry.getName()));
        FileInputStream in = new FileInputStream(fileEntry.getAbsoluteFile());
        int len=0;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
    }
    zos.close();

Upvotes: 0

Related Questions