ZipOutputStream - 压缩包含错误内容的文件

时间:2014-06-23 10:16:57

标签: java zip zipfile zipoutputstream

我可以压缩文件,但内容错误...例如 - a.txt中的内容:
        

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

这是压缩文件的代码:

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

bug在哪里?谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

您正在将字节写入zip文件,从1到10000开始。因此,根据所使用的编码,您显示的输出是正确的。

也许您应该阅读要压缩的文件。以下是您自己修改的代码。

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

答案 1 :(得分:0)

像这样修改你的代码 -

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