如何处理 ZipException(文件密码错误:Demo.zip)并显示适当的消息

How to handle ZipException(Wrong password for file : Demo.zip) and display appropriate messages

由于我是 Java 的新手,我创建了一种解压缩受密码保护的 zip 文件的方法,我使用 zip4j 库来解压缩 zip 文件,密码正确时代码可以正常工作,但是当密码错误时如何处理 ZipException(net.lingala.zip4j.exception.ZipException: net.lingala.zip4j.exception.ZipException: net.lingala.zip4j.exception.ZipException: Wrong Password对于文件:Demo.zip)并显示适当的消息(密码错误!)。请帮忙,这是我的代码。

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
public class UnunzipDemo{

 public void unzipFilesWithPassword(String sourceZipFilePath,String extractedZipFilePath,String password){
  try {
            ZipFile zipFile = new ZipFile(sourceZipFilePath);
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(password);
            }
            zipFile.extractAll(extractedZipFilePath);
            System.out.println("Done");
        }
        catch (ZipException e) {
            e.printStackTrace();
        }
    }

 public static void main(String[] args) {
  String sourceZipFilePath="E:/MyFiles/Files/Zip/Demo.zip";
  String extractedZipFilePath="E:/MyFiles/Files/Unzip/";
  String password="JOEL"; //Correct Password
  UnunzipDemo unzipDemo=new UnunzipDemo();
  unzipDemo.unzipFilesWithPassword(sourceZipFilePath,extractedZipFilePath,password);
 }
}

也许您可以从控制台读取密码。 例如:

    private static String password = "123";

    public static void main(String[] args) {

        // read the input password from console
        // if you have UI, maybe you can read it from some way.
        Scanner sc = new Scanner(System.in);
        String inputPassword = sc.next();
        while (true) {
            //do something...
            try {
                unzip(inputPassword);
                break;
            } catch (Exception e) {
                inputPassword = sc.next();
            }

        }
    }

    private static void unzip(String inputPassword) {
        if (inputPassword.equals(password)) {
            //unzip
        } else {
            // just demo. In your case, this is ZipException
            throw new IllegalArgumentException("wrong password");
        }
    }

您也可以查看错误代码。

public void unzipFilesWithPassword(String sourceZipFilePath,String extractedZipFilePath,String password){
    try {
        ZipFile zipFile = new ZipFile(sourceZipFilePath);
        if (zipFile.isEncrypted()) {
            zipFile.setPassword(password);
        }
        zipFile.extractAll(extractedZipFilePath);
        System.out.println("Done");
    }
    catch (ZipException e) {
        if (e.getCode == ZipExceptionConstants.WRONG_PASSWORD) {
           // Handle wrong password scenario
           System.out.println("Wrong password");
        } else {
           //Handle other exception scenario - printing out error messages?
        }
    }