Friday, December 24, 2010

Count files in direcotry

/*
* 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 Count{
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;
}
File f = new File("C:/Text");
int count = 0;
for (File file : f.listFiles()) {
if (file.isFile()) {
count++;
}
}
System.out.println("Number of files: " + count);


}

0 comments:

Post a Comment