4

java打包文件成压缩包

 3 years ago
source link: https://www.oschina.net/question/4895744_2322554
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java打包文件成压缩包

osc_19984401 发布于 前天 17:32
阅读 105
/**
     * 把文件集合打成zip压缩包
     *
     * @param srcFiles 压缩文件集合
     * @param zipFile  zip文件名
     * @throws RuntimeException 异常
     */
    public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
        long start = System.currentTimeMillis();

        if (zipFile == null) {
            log.error("压缩包文件名为空!");
            return;
        }
        if (!zipFile.getName().endsWith(".zip")) {
            log.error("压缩包文件名异常,zipFile={}", zipFile.getPath());
            return;
        }
        ZipOutputStream zos = null;
        try {
            FileOutputStream out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                FileInputStream in = new FileInputStream(srcFile);
                byte[] bytes = Files.readAllBytes(Paths.get(srcFile.getPath()));
                zos.write(bytes, 0, bytes.length);
                zos.flush();
                zos.closeEntry();
                in.close();
                out.flush();
                out.close();
            }

            long end = System.currentTimeMillis();

            log.info("压缩完成,耗时:" + (end - start) + " ms");

        } catch (Exception e) {
            log.error("ZipUtil toZip exception, ", e);

            throw new RuntimeException("zipFile error from ZipUtils", e);

        }

    }

用以上方法生成压缩包,压缩包里文件内容并没有写入进去,从而生成的文件为0kb,这就导致这段方法毫无意义


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK