javazip4j

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


Since I'm new to Java, I have created a method to unzip password protected zip files, I have used zip4j library for unzipping the zip file,the code works fine when the password is correct, but when the password is wrong how to handle the ZipException(net.lingala.zip4j.exception.ZipException: net.lingala.zip4j.exception.ZipException: net.lingala.zip4j.exception.ZipException: Wrong Password for file: Demo.zip)and display appropriate message(Wrong Password!).Please Help, Here is my code.

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);
	}
}


Solution

  • Maybe you can read the password from console. For instance:

        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");
            }
        }