java.util.zip.ZipOutputStream - 更快地压缩大文件?

时间:2015-07-14 20:32:53

标签: java android zip buffer large-files

我想知道如何在我的Android应用程序中加快40多个图像文件的压缩过程。

客户端正在发送图像,在上传到服务器之前,需要将图像压缩或放入文件夹中。现在我使用波纹管方法,但这种方式文件被压缩约20-30秒,而手机似乎被冻结,用户倾向于退出应用程序:(

我用来压缩的方法:

private static final int BUFFER_SIZE = 2048;

public void zip(String[] files, String zipFile) throws IOException {
        File zipDirectory = new File(Environment.getExternalStorageDirectory()
                + "/laborator/");
        if (!zipDirectory.exists()) {
            zipDirectory.mkdirs();
        } else {
            System.out.println("folder already exists!");
        }

        BufferedInputStream origin = null;
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                new FileOutputStream(Environment.getExternalStorageDirectory()
                        + "/laborator/" + zipFile)));
        try {
            byte data[] = new byte[BUFFER_SIZE];

            for (int i = 0; i < files.length; i++) {
                FileInputStream fi = new FileInputStream(files[i]);
                origin = new BufferedInputStream(fi, BUFFER_SIZE);
                try {
                    ZipEntry entry = new ZipEntry(files[i].substring(files[i]
                            .lastIndexOf("/") + 1));
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
                        out.write(data, 0, count);
                    }
                } finally {
                    origin.close();
                }
            }
        } finally {
            out.close();
            System.out.println("ziping done");
            sendZip();
        }
    }

2 个答案:

答案 0 :(得分:2)

由于您的图像是jpgs,因此您无法在ZIP文件中获得任何适当的压缩。因此,您可以尝试将未压缩的图像放入ZIP文件中,这应该相当快,而不会增加ZIP文件的大小:

ZipEntry entry = new ZipEntry(files[i].subs...
entry.setMethod(ZipEntry.STORED);
out.putNextEntry(entry);

答案 1 :(得分:0)

您可以使用

out.setLevel(Deflater.NO_COMPRESSION);

这种方式无需更改ZipEntry。