Как обрабатывать ZipException (неверный пароль для файла: Demo.zip) и отображать соответствующие сообщения - PullRequest
0 голосов
/ 27 января 2019

Поскольку я новичок в 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);
	}
}

Ответы [ 2 ]

0 голосов
/ 18 мая 2019

Вы также можете проверить код ошибки.

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?
        }
    }
0 голосов
/ 27 января 2019

Может быть, вы можете прочитать пароль с консоли.Например:

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