Find files certain extension java

Find files certain extension java current folder

If you want to find files with certain extension inside folder please use below sample java program. You will two sample java program:

  • FindFilesCertainExtensionCurrentFolder.java: This will find and print list of files which contains *.java extension in current folder only.
  • FindFilesCurrentAndSubDirectory.java: This will find and print all list of files which contains *.java extension in current folder its sub folders.

FindFilesCertainExtensionCurrentFolder.java:

package com.javahonk;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FindFilesCertainExtensionCurrentFolder {

	public static void main(String[] args) {

		List<String> fileList = new ArrayList<String>();

		File folder = new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulService");
		File listOfFiles[] = folder.listFiles();

		for (File file : listOfFiles) {

			String fileName = file.getName();

			if (null != file && fileName.endsWith(".java")) {
				fileList.add(file.getAbsolutePath());
			}
		}
		
		//Print list of file with whose extension is *.java
		if (fileList.size() != 0) {
			System.out.println("Below is list of file with *.java extension\n");
			for (String string : fileList) {
				System.out.println(string);
			}
		}else {
			System.out.println("No file available with extentions *.java in "+folder.getAbsolutePath());
		}

	}

}
  • Output:

2014-11-30_2028

FindFilesCurrentAndSubDirectory.java:

package com.javahonk;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FindFilesCurrentAndSubDirectory {

	public static void main(String[] args) {
		
		File folder = new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulService");
		File listOfFiles[] = folder.listFiles();
		List<String> allFileList = new ArrayList<String>();
		
		for (File file : listOfFiles) {			
			FindFilesRecursively(file, allFileList);
		}
		
		// Print list of file with whose extension is *.java
		if (allFileList.size() != 0) {
			System.out.println("Below is list of file with *.java extension\n");
			for (String string : allFileList) {
				System.out.println(string);
			}
		} else {
			System.out.println("No file available with extentions *.java in " + folder.getAbsolutePath());
		}
		
	}
	
	private static void FindFilesRecursively(File file, List<String> allFileList) {

		if (file.isDirectory()) {
			for (File fileList : file.listFiles()) {
				FindFilesRecursively(fileList, allFileList);
			}
		}
		
		String fileName  = file.getName();		
		if (null != file && fileName.endsWith(".java")) {
			allFileList.add(file.getAbsolutePath());
		}
	}

}
  • Output:

2014-11-30_2107

For more information delete files please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *