由于我是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);
}
}
答案 0 :(得分:0)
也许您可以从控制台读取密码。 例如:
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");
}
}
答案 1 :(得分:0)
您还可以检查错误代码。
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?
}
}