Count the number of files in an archive in java

I am trying to count the number of files in an archive. The problem is that my code counts all objects, including folders (for example, if I have a complex directory, but only one file in it, I cannot check my archive). I am using the size () method.

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");
         } 
     }
 }
+4
source share
2 answers

You can use the method entries()to get Enumeration ZipEntry-s in a zip file and check each one 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;
}
+6
source

I am using the size () method.

. size() all zip . , , :

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

.

+2

Source: https://habr.com/ru/post/1617373/


All Articles