Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,
i want to write an program that returns an interger with the total number of files in a given folder including any files its' subfolder (if any exits)

so how can i do ?

thank !
Posted
Comments
[no name] 18-Jul-12 12:00pm    
Elaborate... how to write a prgram? How to return in integer? How to add numbers? What have you tried?

Why did you not try it? Next time do make an effort and share where are you stuck.

Using recursion:
Java
import java.io.*;

public class CountFilesInDirectory {
        public static void main(String[] args) {
                File f = new File("C:/TestFolder");
                int count = 0;
                for (File file : f.listFiles()) {
                        if (file.isFile()) {
                                count++;
                        }
                }
                System.out.println("Number of files: " + count);
        }
}


Alternate: A simpler one,
Java
new File("/path/to/folder").listFiles().length

Refer: http://docs.oracle.com/javase/6/docs/api/java/io/File.html[^]
 
Share this answer
 
Comments
TorstenH. 19-Jul-12 0:34am    
because it is homework and he does not want to do it himself.
C#
import java.io.File;

public class archu {

  public static void main(String[] args) {

    File folder = new File("c:/Users");
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
      } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
      }
    }
  }

}
 
Share this answer
 
v2
Java
import java.io.*;

public class Number {
        public static void main(String[] args) {
                File f = new File("C:\Users\C:\Users\GULSHAN\Desktop\sarjen");
                int count = 0;
                for (File file : f.listFiles()) {
                        if (file.isFile()) {
                                count++;
                        }
                }
                System.out.println("Number of files: " + count);
        }
   }
 
Share this answer
 
v3
Comments
CHill60 22-Jun-14 15:25pm    
Exactly the same as Solution 1 posted 2 years ago.
[no name] 22-Jun-14 15:29pm    
Do we have an estimate on how many times you are going to answer the same ancient already answered question?
singh_glsn 22-Jun-14 15:37pm    
check solution number 1,,,it shows runtime null pointer exception...but,,not mine...try to find the difference...this just looks same...but,,they are not same..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900