15

using this code

new File("/mnt/sdcard/folder").listFiles().length

returns a sum of folders and files in a particular directory without caring about subdirectories. I want to get number of all files in a directory and its subdirectories.

P.S. : hardly matters if it returns a sum of all the files and folders.

any help appreciated, thanks

jeet.chanchawat
  • 5,842
  • 5
  • 38
  • 59

12 Answers12

37

Try this.

int count = 0;
getFile("/mnt/sdcard/folder/");

private void getFile(String dirPath) {
    File f = new File(dirPath);
    File[] files = f.listFiles();

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

        if (file.isDirectory()) {   
             getFile(file.getAbsolutePath()); 
        }
    }
}

It may help you.

Ziem
  • 6,579
  • 8
  • 53
  • 86
Hemant
  • 759
  • 4
  • 6
  • Note that you could place the `count++` outside of the if/else, because it is increased anyway. Then, there would be no need for the else branch. – Uooo Nov 27 '13 at 08:36
  • Regardless of being selected as the best answer by the OP, this solution is incorrect because it also counts the directories. The original problem was to count the FILES in a directory and subdirectories. The solution provided by Mads Hansen is the best solution posted here. – hfontanez Feb 22 '20 at 19:48
23

You can use recursion.

public static int getFilesCount(File file) {
  File[] files = file.listFiles();
  int count = 0;
  for (File f : files)
    if (f.isDirectory())
      count += getFilesCount(f);
    else
      count++;

  return count;
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
neworld
  • 7,757
  • 3
  • 39
  • 61
22

Using Java 8 NIO:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

  public long fileCount(Path dir) { 
    return Files.walk(dir)
                .parallel()
                .filter(p -> !p.toFile().isDirectory())
                .count();
  }

  public void main(String... args) {
    Path dir = Paths.get(args[0]);
    long count = fileCount(dir);

    System.out.println(args[0] + " has " + count + " files");
  }

}
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • This is great for Java 8+, but can you explain why collect() is necessary? – Alexander Smith Jan 24 '17 at 06:55
  • collect() is a terminal operation, once it is invoked the stream will end, you cannot invoke parallelStream() after collect(). – Dhruv Rai Puri Apr 26 '17 at 16:41
  • Based upon some testing and sampling, I found that I saw a small performance improvement by collecting the items first, then processing in parallel. Depending on how many folders and files within the folders, the answer prior to edits might win out, but updated to a more general solution. – Mads Hansen May 01 '17 at 02:40
  • @MadsHansen The fileCount method should return a long and not an int. – Will Humphreys Jul 07 '17 at 15:03
  • @WillHumphreys thanks, good point. I've updated from int to long. – Mads Hansen Jul 07 '17 at 15:19
  • @MadsHansen doesn't `Files.walk()` throw an `IOException`? It doesn't seem this is being handled in your example. – hfontanez Feb 22 '20 at 19:13
7
public Integer countFiles(File folder, Integer count) {
    File[] files = folder.listFiles();
    for (File file: files) {
        if (file.isFile()) {
            count++;
        } else {
            countFiles(file, count);
        }
    }

    return count;
}

Usage:

Integer count = countFiles(new File("your/path"), Integer.valuOf(0));
Ziem
  • 6,579
  • 8
  • 53
  • 86
Artem Zelinskiy
  • 2,201
  • 16
  • 19
3

you will have to do a recursive search over your files. Use `File#isDrirectory()´ to check if a file is a directory and traverse the file tree down.

Bondax
  • 3,143
  • 28
  • 35
3

You have to go though all the folder recursively and find out the files

int mCount;

getTotalFiles(File dir) {
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            getTotalFiles(file);
        } else {
            mCount++;
        }
    }
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
sujith
  • 2,421
  • 2
  • 17
  • 26
2

Something I've used before, you can easily edit it to get what you want:

public class Filewalker {

    public void walk( String path ) {

        File root = new File( path );
        File[] list = root.listFiles();

        for ( File f : list ) {
            if ( f.isDirectory() ) {
                walk( f.getAbsolutePath() );
                System.out.println( "Dir:" + f.getAbsoluteFile() );
            }
            else {
                System.out.println( "File:" + f.getAbsoluteFile() );
            }
        }
    }

    public static void main(String[] args) {
        Filewalker fw = new Filewalker();
        fw.walk("c:\\" );
    }
}
Buffalo
  • 3,861
  • 8
  • 44
  • 69
2

Here's a short one all encapsulated within a single method just returning the number of files and directories within a specific directory:

public static int countFiles(File directory) {
    int count = 0;
    for (File file : directory.listFiles()) {
        if (file.isDirectory()) {
            count += countFiles(file); 
        }
        count++;
    }
    return count;
}

Cheers!

Ziem
  • 6,579
  • 8
  • 53
  • 86
salocinx
  • 3,715
  • 8
  • 61
  • 110
2

Just for the record, you may also use iteration instead of recursion:

public static int countFiles(final File dir) {
    final ArrayDeque<File> dirs = new ArrayDeque<>();
    dirs.add(dir);
    int cnt = 0;
    while (!dirs.isEmpty()) {
        final File[] files = dirs.poll().listFiles();
        for (final File f: files)
            if (f.isDirectory())
                dirs.add(f);
            else
                ++cnt;
    }
    return cnt;
}

In this implementation I'm using ArrayDeque but you can use any Queue or any List for the job.

gthanop
  • 3,035
  • 2
  • 10
  • 27
1
public int numberOfFiles(File srcDir) {
    int count = 0;
    File[] listFiles = srcDir.listFiles();
    for(int i = 0; i < listFiles.length; i++){
        if (listFiles[i].isDirectory()) {
            count += numberOfFiles(listFiles[i]);
        } else if (listFiles[i].isFile()) {
            count++;
        }
    }
    return count;
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
kishore
  • 41
  • 3
1

http://www.java2s.com/Code/Java/File-Input-Output/Countfilesinadirectoryincludingfilesinallsubdirectories.htm

public static int countFilesInDirectory(File directory) {
  int count = 0;
  for (File file : directory.listFiles()) {
      if (file.isFile()) {
          count++;
      }
      if (file.isDirectory()) {
          count += countFilesInDirectory(file);
      }
  }
  return count;
}

refer this site

it gives perfect answer

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
jayakumar
  • 11
  • 1
1
import java.io.File;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {


     Scanner sc=new Scanner(System.in);  

     System.out.println("Enter the Path for Directory/Folder Name");  
     String Directory=sc.nextLine(); 
     System.out.println("Your Directory/folder is :"+Directory);

     File f = new File(Directory);

     int countFiles = 0;
     int countDirectory=0;
     for (File file : f.listFiles()) {
             if (file.isFile()) {
                     countFiles++;
             }
             if (file.isDirectory()) {
                     countDirectory++;
             }

     }
     System.out.println("Number of files in Directory : " + countFiles+"\nNumber of Sub-directories "+countDirectory);

    }

}
Orin
  • 920
  • 5
  • 16