Hi,
Here is a small program that i have written to list directories recursively and also the count of files in each directory and output the same to console or to a file as per user preferences.
Usage: java ListFiles directory_to_scan [outputfile]
You can use this code if you really like and i dont impose any license restriction or something :)
But i will appreciate if you just send me a mail that you are benefitted by this simple piece of code.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ListFiles {
private static List filesList = new ArrayList();
public static void main(String args[]) {
if(args.length ==0) {
System.out.println("Usage: ListFiles directory [outputfile]");
System.exit(-1);
}
String directoryName = args[0];
String outputFile = null;
if(args.length == 2) {
outputFile = args[1];
}
if(directoryName != null && !directoryName.isEmpty()) {
File directory = new File(directoryName);
if(directory.isDirectory()) {
File[] files = directory.listFiles();
int fileCount = directory.listFiles(new DirectoryNameFilter()).length;
filesList.add(directory.getAbsolutePath() + " = " + fileCount);
getFilesCount(directory);
}
if(outputFile != null) {
File output = new File(outputFile);
BufferedWriter bufWriter = null;
try {
bufWriter = new BufferedWriter(new FileWriter(output));
for(String fileName: filesList) {
bufWriter.write(fileName + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(bufWriter != null) {
try {
bufWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} else {
for(String fileName: filesList) {
System.out.println(fileName);
}
}
}
}
private static List getFiles(File directory) {
List fileList = new ArrayList();
File files[] = null;
if(directory.isDirectory()) {
files = directory.listFiles();
for(File file:files) {
if(file.isDirectory()) {
fileList=getFiles(file);
} else {
filesList.add(file.getAbsolutePath());
}
}
}
return fileList;
}
private static void getFilesCount(File directory) {
File files[] = null;
int fileCount = 0;
if(directory.isDirectory()) {
files = directory.listFiles();
for(File file:files) {
if(file.isDirectory()) {
fileCount = file.listFiles(new DirectoryNameFilter()).length;
filesList.add(file.getAbsolutePath() + " = " + fileCount);
getFilesCount(file);
}
}
}
}
}
class DirectoryNameFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
if(!new File(dir,name).isDirectory()) {
return true;
} else {
return false;
}
}
}