使用Java8压缩文件

Java大约 1223 字

Java8

public class ZipFile {

    public static Path zip(String dirPath, String zipFilePath) throws IOException {
        Path zipFile = Files.createFile(Paths.get(zipFilePath));

        Path sourceDirPath = Paths.get(dirPath);
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile));
             Stream<Path> paths = Files.walk(sourceDirPath)) {
            paths.filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(sourceDirPath.relativize(path).toString());
                        try {
                            zipOutputStream.putNextEntry(zipEntry);
                            Files.copy(path, zipOutputStream);
                            zipOutputStream.closeEntry();
                        } catch (IOException ignore) {
                        }
                    });
        }
        System.out.println("Zip is created at : " + zipFile);
        return zipFile;
    }

    public static void main(String[] args) throws IOException {
        zip("D:\\dir", "D:\\test.zip");
    }

}

完整代码

https://github.com/fendoudebb/learning/tree/master/java/learn-java8/zip/src

阅读 174 · 发布于 2020-05-28

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批