0

我可以压缩文件,但内容错误......例如 - 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();
    }

错误在哪里?感谢帮助。

4

2 回答 2

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();
    }
于 2014-06-23T10:35:18.683 回答
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();
于 2014-06-23T10:26:17.793 回答