I know its late and there are lots of answers but this zip4j is one of the best libraries for zipping I have used. Its simple (no boiler code) and can easily handle password protected files.
private void extractFolder(String zipFile,String extractFolder)
{
try
{
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = extractFolder;
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
//destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory())
{
BufferedInputStream is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
}
catch (Exception e)
{
Log("ERROR: "+e.getMessage());
}
}
Extract zip file and all its subfolders, using only the JDK:
private void extractFolder(String zipFile,String extractFolder)
{
try
{
int BUFFER = 2048;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = extractFolder;
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements())
{
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
//destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory())
{
BufferedInputStream is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
}
catch (Exception e)
{
Log("ERROR: "+e.getMessage());
}
}
It has the standard packing and unpacking functionality (on streams and on filesystem) + lots of helper methods to test for files in an archive or add/remove entries.
Full Implementation to Zip/Unzip a Folder/File with zip4j
Add this dependency to your build manager. Or, download the latest JAR file from here and add it to your project build path. The class bellow can compress and extract any file or folder with or without password protection-
import java.io.File;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.lingala.zip4j.core.ZipFile;
public class Compressor {
public static void zip (String targetPath, String destinationFilePath, String password) {
try {
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if (password.length() > 0) {
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
ZipFile zipFile = new ZipFile(destinationFilePath);
File targetFile = new File(targetPath);
if (targetFile.isFile()) {
zipFile.addFile(targetFile, parameters);
} else if (targetFile.isDirectory()) {
zipFile.addFolder(targetFile, parameters);
} else {
//neither file nor directory
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password) {
try {
ZipFile zipFile = new ZipFile(targetZipFilePath);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destinationFolderPath);
} catch (Exception e) {
e.printStackTrace();
}
}
/**/ /// for test
public static void main(String[] args) {
String targetPath = "target\\file\\or\\folder\\path";
String zipFilePath = "zip\\file\\Path";
String unzippedFolderPath = "destination\\folder\\path";
String password = "your_password"; // keep it EMPTY<""> for applying no password protection
Compressor.zip(targetPath, zipFilePath, password);
Compressor.unzip(zipFilePath, unzippedFolderPath, password);
}/**/
}
TrueZIP is a Java based plug-in framework for virtual file systems (VFS) which provides transparent access to archive files as if they were just plain directories
Another option is JZlib. In my experience, it's less "file-centered" than zip4J, so if you need to work on in-memory blobs rather than files, you may want to take a look at it.
发布评论
评论(9)
我知道已经晚了并且有很多答案,但是这个 zip4j 是我使用过的最好的压缩库之一。它很简单(没有锅炉代码)并且可以轻松处理受密码保护的文件。
Maven 依赖项是:
I know its late and there are lots of answers but this zip4j is one of the best libraries for zipping I have used. Its simple (no boiler code) and can easily handle password protected files.
The Maven dependency is:
在 Java 8 中,使用 Apache Commons-IO 的
IOUtils
你可以这样做:它仍然是一些样板代码,但它只有 1 个非外来依赖项:
IOUtils
maven.org/#search%7Cgav%7C1%7Cg%3A%22commons-io%22%20AND%20a%3A%22commons-io%22" rel="noreferrer">Commons-IO在 Java 11 及更高版本中,可能有更好的选项,请参阅 ZhekaKozlov 的评论。
In Java 8, with Apache Commons-IO's
IOUtils
you can do this:It's still some boilerplate code, but it has only 1 non-exotic dependency: Commons-IO
In Java 11 and higher, better options might be available, see ZhekaKozlov's comment.
仅使用 JDK 提取 zip 文件及其所有子文件夹:
Zip 文件及其所有子文件夹:
Extract zip file and all its subfolders, using only the JDK:
Zip files and all its subfolders:
您可以查看的另一个选项是 zt-zip,可从 Maven 中心和项目页面获取 https:// github.com/zeroturnaround/zt-zip
它具有标准的打包和解包功能(在流和文件系统上)+许多帮助方法来测试存档中的文件或添加/删除条目。
Another option that you can check out is zt-zip available from Maven central and project page at https://github.com/zeroturnaround/zt-zip
It has the standard packing and unpacking functionality (on streams and on filesystem) + lots of helper methods to test for files in an archive or add/remove entries.
使用 zip4j 完整实现压缩/解压缩文件夹/文件
添加 此依赖项到您的构建管理器。或者,从此处和将其添加到您的项目构建路径。下面的
class
可以压缩和提取任何有或没有密码保护的文件或文件夹 -更详细的使用方法,请参阅此处。
Full Implementation to Zip/Unzip a Folder/File with zip4j
Add this dependency to your build manager. Or, download the latest JAR file from here and add it to your project build path. The
class
bellow can compress and extract any file or folder with or without password protection-For more detailed usage, please see here.
TrueZip 是一个非常好的项目。
(例如,来自 网站):
A very nice project is TrueZip.
For example (from the website):
另一个选择是 JZlib。根据我的经验,它不像 zip4J 那样“以文件为中心”,因此如果您需要处理内存中的 blob 而不是文件,您可能需要看一下它。
Another option is JZlib. In my experience, it's less "file-centered" than zip4J, so if you need to work on in-memory blobs rather than files, you may want to take a look at it.
这里有一个递归压缩和解压缩文件的完整示例:
http:// /developer-tips.hubpages.com/hub/Zipping-and-Unzipping-Nested-Directories-in-Java-using-Apache-Commons-Compress
There's a full example here for zipping and unzipping files recursively:
http://developer-tips.hubpages.com/hub/Zipping-and-Unzipping-Nested-Directories-in-Java-using-Apache-Commons-Compress
您查看过 http://commons.apache.org/vfs/ 吗?它声称可以为您简化很多事情。但我从来没有在项目中使用过它。
除了 JDK 或 Apache Compression 之外,我也不知道还有 Java-Native 压缩库。
我记得有一次我们从 Apache Ant 中剥离了一些功能 - 它们内置了很多用于压缩/解压缩的实用程序。
使用 VFS 的示例代码如下所示:
Did you have a look at http://commons.apache.org/vfs/ ? It claims to simplify a lot of things for you. But I've never used it in a project.
I also am not aware of Java-Native compression libs other than the JDK or Apache Compression.
I remember once we ripped some features out of Apache Ant - they have a lot of utils for compression / decompression built in.
Sample code with VFS would look like: