Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count the number of files in archive in java

Tags:

java

file

count

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");
         } 
     }
 }
like image 397
Jack Avatar asked Nov 25 '15 07:11

Jack


2 Answers

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;
}
like image 189
ruakh Avatar answered Sep 28 '22 05:09

ruakh


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

  • https://docs.oracle.com/javase/8/docs/api/java/util/zip/ZipFile.html#entries
  • https://docs.oracle.com/javase/8/docs/api/java/util/zip/ZipEntry.html#isDirectory
like image 34
Andreas Fester Avatar answered Sep 28 '22 07:09

Andreas Fester