Get files from a directory in the file system using Java

If provided, any files matching any one of the strings found in the array of string ignore[] will be ignored; this can be useful if you want pick up all files except, for example, those marked with the word “temp” or obsolete files marked with “.old” extension.

/**
 * Get the all files in a directory, ignoring files with file names containing particular strings.
 *
 * @param folderPath : Full path of directory in question, eg. "C:\docs\myFiles\"
 * @param ignore[] : An array of strings containing words with which to ignore files, eg. { "temp","ignore",".old" }
 * @return File[]
 * @author C. Peter Chen of http://dev-notes.com
 * @date 20080610
 */
private static File[] getFiles(String folderPath, String ignore[]) {
	File f = new File(folderPath);
	File[] fList = f.listFiles();
	List retFl = new ArrayList();
	if (fList != null && fList.length > 0) {
		for (File file : fList) {
			boolean pass = true;
			for (String ig : ignore) {
				if (file.getName().indexOf(ig) >= 0) {
					pass = false;
				}
			}
			if (pass) { // Only get the file if none of the ignore strings are present
				retFl.add(file);
			}
		}
	}
	return retFl.toArray(new File[0]);
}

Leave a Reply

Your email address will not be published.