snippetjournal

– notes, snippet codes, and my journal

Archive for August 2012

Count Files in Folder and Subfolder With Java

with 2 comments

this sample of code only for noob like me πŸ˜€

import java.io.File;

public class CountFiles {

	public CountFiles() {
	}

	/*
	 * 2) Write a solution that returns an Integer with the total number of files in a given folder
	 * including any files in its’ sub- folders (if any exist).
	 *
	 * */

	public int countFile(int count, String path, boolean isrecursive) {
		if (!isrecursive)
			count = 0;

		File file = new File(path);
		File[] childFile = file.listFiles();

		if (childFile != null) {
			for (int k = 0; k < childFile.length; k++) {
				if (childFile[k].isDirectory()) {
					count = countFile(count, childFile[k].toString(), true);
				} else {
					count++;
				}
			}
		}

		System.out.println("count = " + count);
		return count;
	}

}

below is the codes that i customizes to count specific file type, is not a good codes though πŸ˜€

public int countFile(int count, String path, boolean isrecursive, String fileType) {
		if (!isrecursive)
			count = 0;

		File file = new File(path);
		File[] childFile = file.listFiles();

		if (childFile != null) {
			for (int k = 0; k < childFile.length; k++) {
				if (childFile[k].isDirectory()) {
					System.out.println("path " + childFile[k].getPath());
					count = countFile(count, childFile[k].toString(), true, fileType);
				} else {
					if (fileType != "" && childFile[k].getName().toLowerCase().contains("."+fileType)) {
						System.out.println("filename "+ childFile[k].getName().toLowerCase());
						count++;
					}else if(fileType == ""){
						count++;
					}

				}
			}
		}

		System.out.println("count = " + count);
		return count;
	}
countFiles.countFile(0, "E:\\aaaa", false, "txt");

Advertisements

Written by snippetjournal

August 21, 2012 at 2:54 am

Posted in Programming

Tagged with , , ,