Graham Graham - 2 years ago 90
Java Question

Check file distribution across directories


I have an application that is creating a number of subfolders in a fixed directory. Across those directories it is putting a number of files. The number of files is equally distributed across those folders. I have a test that checks for a fixed value across the folders, so n files in each folder.


How can i test that, where there are 4 subfolders and 5 messages the distribution of messages across those 4 subfolders is 2 messages in 1 folder and 1 message in the other 3?

Source Code

public boolean checkFileCountInEachFolder(int expectedCount){
File folder = new File(AppProperties.getInstance().get("path"));
File[] files = folder.listFiles();

if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];

if (file.isDirectory()) {
int fileCount = listFiles(file, new ArrayList<File>()).size();
if (fileCount!=expectedCount) {
return false;

return true;

Answer Source

There are many ways to do it, here is one of them.

First, list the subdirectories with a FileFilter .

Divide the number of messages (the method's parameter being the number of messages) , by the number of folders, to get the minimum expected occurences (may be 0) .

Since you are equally distributing, the max number of occurences can't be more than the min + 1.

Check that the number of files in each subfolder is in this range (or is simply equal to min or to max, in this particular case).

Finally, sum the count of all files found, and compare the result to the total number of messages .

public boolean checkFileCountInEachFolder(final int nbMessages) {

    File folder = new File(AppProperties.getInstance().get("path"));

    File[] subFolders = folder.listFiles(new FileFilter() {
        public boolean accept(final File f) {
            return f.isDirectory();

    int nbFolders = subFolders.length;
    int minOccurences = nbMessages / nbFolders;
    int maxOccurences = minOccurences + 1;

    int totalCount = 0;

    for (int i = 0; i < subFolders.length; i++) {
        File file = subFolders[i];

        int fileCount = listFiles(file, new ArrayList<File>()).size();
        if (fileCount < minOccurences || fileCount > maxOccurences) {
            return false;

        totalCount += fileCount;


    return (totalCount == nbMessages);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download