Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.File;

public class Main {
    /**
     * @param file
     * @return
     */
    public static int getNumFilesInFolder(File file) {
        if (file == null) {
            throw new NullPointerException("file cannot be null");
        }
        if (!file.exists()) {
            throw new NullPointerException("file does not exist");
        }
        if (file.isFile()) {
            throw new ClassCastException("file is not a directory");
        }
        return getSubfilesNumberInFolder(file, false, true);
    }

    /**
     * @param file
     * @param includeHiddleFiles
     * @param includeFolder
     * @return
     */
    public static int getNumFilesInFolder(File file, boolean includeHiddleFiles, boolean includeFolder) {
        if (file == null) {
            throw new NullPointerException("file cannot be null");
        }
        if (!file.exists()) {
            throw new NullPointerException("file does not exist");
        }
        if (file.isFile()) {
            throw new ClassCastException("file is not a directory");
        }
        return getSubfilesNumberInFolder(file, includeHiddleFiles, includeFolder);
    }

    /**
     * @param file
     * @param includeHiddleFiles
     * @param includeFolder
     * @return
     */
    public static int getNumFilesInFolder(File[] files, boolean includeHiddleFiles, boolean includeFolder) {
        int size = 0;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isFile()) {
                size++;
            } else if (file.isDirectory()) {
                size += getNumFilesInFolder(file, includeHiddleFiles, includeFolder);
            }
        }
        return size;
    }

    /**
     * @param file
     * @param includeHiddleFiles
     * @param includeFolder
     * @return
     */
    private static int getSubfilesNumberInFolder(File file, boolean includeHiddleFiles, boolean includeFolder) {
        int size = 0;
        File[] files = file.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File file2 = files[i];
                if (!includeHiddleFiles && file2.isHidden()) {
                    continue;
                }
                if (file2.isDirectory()) {
                    size += getSubfilesNumberInFolder(file2, includeHiddleFiles, includeFolder);
                } else {
                    size += 1;
                }
            }
        }
        if (includeFolder) {
            size++;
        }
        return size;
    }
}