Java 8 压缩文件夹示例

前言

Java 8 压缩文件夹示例

在本篇文章中,我将向大家展示如何使用Java 8的核心包实现压缩文件夹,该核心包在jdk的:java.util.zip包下,首先我们准备个待压缩的文件夹,如下图:
Java 8 压缩文件夹示例_第1张图片
将源文件夹的路径设置为“ D:\note”,程序将所有文件压缩为note.zip。 我们使用资源块尝试包裹了Files.walk,以便可以关闭流。

压缩文件夹示例

package github.javaguide.springsecurityjwtguide;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringSecurityJwtGuideApplicationTests {

	private List <String> fileList;
    private static final String NOTES_ZIP = "D:\\note.zip";
    private static final String FOLDER_TO_ZIP = "D:\\note";

    public static void main(String[] args) throws IOException {
        zip(FOLDER_TO_ZIP,NOTES_ZIP);
    }
	
    /**
     * 压缩文件夹
     * @param sourcNoteseDirPath 文件夹路径
     * @param zipFilePath 压缩包路径
     * @throws IOException
     */
	public static void zip(final String sourcNoteseDirPath, final String zipFilePath) throws IOException {
        Path zipFile = Files.createFile(Paths.get(zipFilePath));

        Path sourceDirPath = Paths.get(sourcNoteseDirPath);
        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 e) {
                    System.err.println(e);
                }
            });
        }
        System.out.println("Zip is created at : "+zipFile);
    }
}

输出

Zip is created at : D:\note.zip

你可能感兴趣的:(Java后端,PDF水印)