Hello,
How would I count the number of files in a directory? Thanks!

Recommended Answers

All 9 Replies

listFiles() and use the length of the returned array?

See the API docs for File.

I did look it up, even before the first time you told me too. But I am still having trouble figuring it out. How do I used the array listFiles returns?

How do you normally use an array?

String[] files = file.listFiles();
int numFiles = files.length;

oooh lol now i feel dumb. Thanks!

Also note that directories will also be included and can be discerned with file.isDirectory(). If you need to include file counts from subdirectories, you'll need to do the recursion yourself.

Also note that directories will also be included and can be discerned with file.isDirectory(). If you need to include file counts from subdirectories, you'll need to do the recursion yourself.

I am writing a program that should return the number of files in a user specified directory. I have a sample program that returns the size of a directory. How would I go about changing it to return the number of files? (You referred to it in this post.)

/*
 * CSCI 2410
 * Meghan E. Hembree
 * Friday, September 3, 2010, 11:00:00am
 *
 * Description: (Number of files in a directory)  Write a program that
 * prompts the user to enter a directory and displays the number of the
 * files in the directory.
 *
 */
package exercise20_29;

import java.io.File;
import java.util.Scanner;

public class Exercise20_29 {

    public static void main(String[] args) {
        //Prompt the user to enter a directory or a file
        System.out.print("Enter a directory or a file: ");
        Scanner input = new Scanner(System.in);
        String file = input.nextLine();

        //Display the size
        System.out.println(getSize(new File(file)) + " files");
    }

    public static long getSize(File file){
        //Store the total size of all files
        long size = 0;

        if(file.isDirectory()){
            //All files and subdirectories
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++){
                //Recursive call
                size += getSize(files[i]);
            }
        }
        //Base case
        else{
            size += file.length();
        }

        return size;
    }

}

You can count them recursively the same way you determined the total size. I assume you don't want to include directories in that count.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.