Search code examples
javazipextractpassword-protectionzip4j

I am trying to extract password-protected ZIP files using zip4j jar file but i am getting error for following


I am very new to Java and I am trying to extract password-protected ZIP file using java and I have written code for the same but I am getting error for few methods such as isEncrypted(), fileHeaderList(), extractFile(), I searched for few related posts/issues but did not find the exact resolution. Can anyone of you help me in this issue

 import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipFile;
    import net.lingala.zip4j.model.FileHeader;

    public class Extraction {
    public Extraction() {

            try {
                ZipFile zipFile = new ZipFile("C:\\Users\\rajesh\\Desktop\\ZipFile\\file1.zip");

                //Error for isEncrypted() "The method isEncrypted() is undefined for the type ZipFile"
                if (zipFile.isEncrypted()) {
                                        zipFile.setPassword("MYPASS!");
                }

                //The method getFileHeaders() is undefined for the type ZipFile
                List fileHeaderList = zipFile.getFileHeaders();

                                for (int i = 0; i < fileHeaderList.size(); i++) {
                    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);
        //The method extractFile(FileHeader, String) is undefined for the type ZipFile                              
zipFile.extractFile(fileHeader, "C:\\Users\\rajesh\\Desktop\\ZipFile");
                }

            } catch (Exception e) {
                System.out.println("Please Try Again");
            }

        }

        public static void main(String[] args) {
            new Extraction();

        }

    }

Solution

  • You have imported java.util.zip.ZipFile and are attempting to call methods on it which do not exist. You can find the ZipFile's API via the link I provided above. As you also imported net.lingala.zip4j.model.FileHeader I guess you wanted to use a different zip library than the one found under java.util.zip. So in order to solve your problem you have to clean up your imports. You most likely need to delete the import statements for the package java.util.zip and need to import the appropriate classes from net.lingala.zip4j.*.