在 Java 中提取 ZIP 文件并删除密码保护,你可以使用 java.util.zip 包中的 ZipInputStream 类。请注意,这只适用于标准的 ZIP 加密,而不是其他加密算法。
java.util.zip
ZipInputStream
以下是一个简单的示例,展示如何提取 ZIP 文件并删除密码保护:
import java.io.*; import java.util.zip.*; public class UnzipPasswordProtectedZip { public static void main(String[] args) { String zipFilePath = "path/to/password_protected.zip"; String destinationPath = "path/to/extracted_files"; String password = "your_password"; try { unzip(zipFilePath, destinationPath, password); } catch (IOException e) { e.printStackTrace(); } } public static void unzip(String zipFilePath, String destinationPath, String password) throws IOException { try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) { byte[] buffer = new byte[1024]; while (true) { ZipEntry entry = zipInputStream.getNextEntry(); if (entry == null) { break; // No more entries } String entryName = entry.getName(); String outputPath = destinationPath + File.separator + entryName; if (entry.isDirectory()) { File dir = new File(outputPath); dir.mkdirs(); } else { try (OutputStream outputStream = new FileOutputStream(outputPath)) { int length; while ((length = zipInputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } } zipInputStream.closeEntry(); } } catch (ZipException e) { // If the zip file is password protected, handle the exception accordingly if (e.getMessage().contains("Password required")) { System.out.println("Password protected ZIP file. Password is required."); // You can attempt to unzip with the provided password here // For simplicity, this example does not handle password-protected ZIP files } else { throw e; } } } }
在这个示例中,unzip 方法用于解压缩 ZIP 文件。如果 ZIP 文件受密码保护,将捕获 ZipException,并检查异常消息是否包含 "Password required"。如果是,则可以尝试使用提供的密码进行解压缩。请注意,这里仅仅是示例,实际上处理密码保护 ZIP 文件时需要更复杂的逻辑。
unzip
ZipException
原文链接:codingdict.net