Jack
Jack

Reputation: 209

count the number of files in archive in java

I am trying to count the number of files in archive . The problem that my code count all entities including folders ( for example if I have complex directory but only one file in it I cant validate my archive). I use method size().

import java.nio.file.Path;
import javax.enterprise.context.Dependent;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import ru.cntp.eupp.roster.Notification;
import java.util.ArrayList;
import java.util.zip.ZipFile;
import java.util.List;
import java.util.Enumeration;

/*
 * @author dfaevskii
 */
@Dependent
public class ZipValidator {

     public void validate(Path pathToFile) throws IOException {

         ZipFile zipFile = new ZipFile(pathToFile.toFile());

         if (zipFile.size() != 1 && zipFile.size() != 2) {
             throw new InvalidZipException("The number of files in archive is more than  2");
         } 
     }
 }

Upvotes: 7

Views: 9702

Answers (2)

ruakh
ruakh

Reputation: 183504

You can use the entries() method to get an Enumeration of the ZipEntry-s in the zip-file, and check each one to see if it isDirectory():

int countRegularFiles(final ZipFile zipFile) {
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    int numRegularFiles = 0;
    while (entries.hasMoreElements()) {
        if (! entries.nextElement().isDirectory()) {
            ++numRegularFiles;
        }
    }
    return numRegularFiles;
}

Upvotes: 10

Andreas Fester
Andreas Fester

Reputation: 36650

I use method size().

That is the issue. size() returns the number of all entries in the zip file. To count the number of entries without directories, you need to iterate the entries and check whether its a directory or not:

...
int count = 0;
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
    ZipEntry entry = zipEntries.nextElement();
    if (!entry.isDirectory()) {
       count++;
    }
}
...

See also

Upvotes: 4

Related Questions