使用 Java8 压缩文件

Java 压缩 About 1,224 words

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

Views: 3,500 · Posted: 2020-05-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh