Java11 zip4jでzipファイルの解凍・圧縮を行うサンプル

環境
Java 17
Gradleプロジェクト

1.zip4jの導入
Gradleプロジェクトの場合

build.gradle
implementation group: 'net.lingala.zip4j’, name: 'zip4j’, version: '2.6.2’

Mavenプロジェクトの場合
pom.xml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.6.2</version>
</dependency>
<dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>2.6.2</version> </dependency>
<dependency>
    <groupId>net.lingala.zip4j</groupId>
    <artifactId>zip4j</artifactId>
    <version>2.6.2</version>
</dependency>

2.zipファイルを解凍する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// zipファイルを解凍する場合
new ZipFile("result.zip").extractAll("/data/ct/ark");
// パスワード付きzipファイルを解凍する場合
new ZipFile("result.zip", "password".toCharArray()).extractAll("/data/ct/ark");
// zipファイルを解凍する場合 new ZipFile("result.zip").extractAll("/data/ct/ark"); // パスワード付きzipファイルを解凍する場合 new ZipFile("result.zip", "password".toCharArray()).extractAll("/data/ct/ark");
// zipファイルを解凍する場合
new ZipFile("result.zip").extractAll("/data/ct/ark");

// パスワード付きzipファイルを解凍する場合
new ZipFile("result.zip", "password".toCharArray()).extractAll("/data/ct/ark");

 

3.zipファイルに圧縮する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 1つのファイルをzipファイルに圧縮する場合
new ZipFile("result.zip").addFile(new File("file.txt"));
// 複数のファイルをzipファイルに圧縮する場合
new ZipFile("result.zip").addFiles(Arrays.asList(new File("11.txt"), new File("22.txt")));
// ディレクトリをzipファイルに圧縮する場合
new ZipFile("result.zip").addFolder(new File("/data/ct/ark"));
// 1つのファイルをzipファイルに圧縮する場合 new ZipFile("result.zip").addFile(new File("file.txt")); // 複数のファイルをzipファイルに圧縮する場合 new ZipFile("result.zip").addFiles(Arrays.asList(new File("11.txt"), new File("22.txt"))); // ディレクトリをzipファイルに圧縮する場合 new ZipFile("result.zip").addFolder(new File("/data/ct/ark"));
// 1つのファイルをzipファイルに圧縮する場合
new ZipFile("result.zip").addFile(new File("file.txt"));

// 複数のファイルをzipファイルに圧縮する場合
new ZipFile("result.zip").addFiles(Arrays.asList(new File("11.txt"), new File("22.txt")));

// ディレクトリをzipファイルに圧縮する場合
new ZipFile("result.zip").addFolder(new File("/data/ct/ark"));

 

IT

Posted by arkgame