snippetjournal

– notes, snippet codes, and my journal

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");

Written by snippetjournal

August 21, 2012 at 2:54 am

Posted in Programming

Tagged with , , ,

2 Responses

Subscribe to comments with RSS.

  1. Beautiful solution .. Maybe you can extend your source code by only counting for particular file such as .txt !

    pursuitmyhappiness

    February 18, 2014 at 12:49 pm

    • hello nizar, maybe u can customize the codes if u want to count specific file, u can read about File object reference in oracle site😛

      snippetjournal

      February 19, 2014 at 7:06 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: