Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfBoundsException when reading from a ZipInputStream Java

I'm trying to implement this algorithm description from a previous question I had here in stackoverflow:

suppressing or not allowing the access time to be modified java

so I implemented as

byte[] digest = new byte[this.BUFFER];
        MessageDigest md5;

        try {
            md5 = MessageDigest.getInstance("MD5");

            while(entry.getNextEntry() != null){

                ZipEntry current = entry.getNextEntry();

                if(current.isDirectory()){
                    digest = this.encodeUTF8(current.getName());
                    md5.update(digest);
                }
                else{
                        entry.read(digest, 0, this.BUFFER);
                        md5.update(digest);
                }
            }
            digest = md5.digest();
            entry.close();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

However, I'm getting a Exception in thread "main" java.lang.IndexOutOfBoundsException in the else statement. Does someone know why? Also, could you please tell me if my algorithm was correctly implemented?

like image 373
cybertextron Avatar asked Mar 08 '26 02:03

cybertextron


1 Answers

You're calling getNextEntry() twice, instead of once:

while (entry.getNextEntry() != null) { // goes to the next entry
    ZipEntry current = entry.getNextEntry(); // goes to the next entry

Use this instead:

ZipEntry current;
while ((current = entry.getNextEntry()) != null) {
    // use current   
}

or

for (ZipEntry current = entry.getNextEntry(); current != null; current = entry.getNextEntry()) {
    // use current
}
like image 197
JB Nizet Avatar answered Mar 10 '26 14:03

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!