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

    由于我是 Java 新手,我创建了一种解压缩受密码保护的 zip 文件的方法,我使用 zip4j 库来解压缩 zip 文件,密码正确时代码工作正常,但密码错误时如何处理ZipException(net.lingala.zip4j.exception.ZipException:net.lingala.zip4j.exception.ZipException:net.lingala.zip4j.exception.ZipException:文件密码错误: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);

    }

}


慕勒3428872
浏览 158回答 2
2回答

暮色呼如

也许您可以从控制台读取密码。例如:    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");        }    }

FFIVE

您还可以检查错误代码。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?        }    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java