Java directoryfrom (e.g. time, place, numerical quantity)recursiveSearch for files in
Java introduces a sample program that recursively searches for files in a specified directory, including subdirectories, and obtains a list of files that match the search criteria.
They are equivalent to the UNIX command ls -R or the Windows command dir /s.
You can also specify * as a wildcard character in the file name to be searched, or use a regular expression to search.
As an example of usage, the following recursively searches the directory filelist, including subdirectories, to obtain a list of files with the extension java.
File[] files = search.listFiles("C:/filelist/", "*.java");
sample program
/**
*
*/
public class FileSearch {
public static final int TYPE_FILE_OR_DIR = 1;
public static final int TYPE_FILE = 2;
public static final int TYPE_DIR = 3;
/**
* From the specified directory [directoryPath],
* Search the file [fileName] to be searched recursively and find the corresponding file.
* Returns a list of file objects.
*
* example)
* File[] files =listFiles(“C:/filelist/”, “*.java”);
* The example above searches the directory filelist recursively and
* Get a list of files with the extension java.
*
* @param directoryPath Path representing the directory to search
* @param fileName File name to search for
* You can specify * as a wildcard character in the file name.
* @return File object matching the search
*/
public File[] listFiles(String directoryPath, String fileName) {
// Convert * as wildcard character to regular expression
if (fileName != null) {
fileName = fileName.replace(“.”, “\\.”);
fileName = fileName.replace(“*”, “.*”);
}
return listFiles(directoryPath, fileName, TYPE_FILE, true, 0);
}
/**
* From the specified directory [directoryPath], specified as a regular expression
* Search recursively for the file to be searched [fileNamePattern],
* Returns a list of applicable file objects.
*
* You can also use the search condition to determine whether the file's update date has passed the specified number of days.
* Can be specified.
*
* example)
* File[] files =
* listFiles(“C:/filelist/”, “*.java”,TYPE_FILE, true, 2);
* In the above example, the directory filelist is searched recursively and updated less than 7 days ago.
* Get a list of files with extension java.
*
* @param directoryPath Path representing the directory to search
* @param fileNamePattern File name to search for [regular expression]
* @param type The corresponding file object is specified by [type].
* The following can be specified
* TYPE_FILE_OR_DIR・・・File and directory
* TYPE_FILE・・・File
* TYPE_DIR・・・Directory
* @param isRecursive true to search recursively
* @param period Search for files whose update date has passed the specified number of days.
* Can be set whether or not
* Not applicable if 0
* If 1 or more, search files after the specified number of days
* If less than -1, search files older than the specified number of days
* @return File object matching the search
*/
public File[] listFiles(String directoryPath,
String fileNamePattern, int type,
boolean isRecursive, int period) {
File dir = new File(directoryPath);
if (!dir.isDirectory()) {
throw new IllegalArgumentException
(“Path specified in argument[” + dir.getAbsolutePath() +
“] is not a directory.”);
}
File[] files = dir.listFiles();
// its output
for (int i = 0; i < files.length; i++) {
File file = files[i];
addFile(type, fileNamePattern, set, file, period);
// Search recursively and add to list recursively if it is a directory
if (isRecursive && file.isDirectory()) {
listFiles(file.getAbsolutePath(), fileNamePattern,
type, isRecursive, period);
}
}
return (File[]) set.toArray(new File[set.size()]);
}
private void addFile(int type, String match, TreeSet set,
File file,int period) {
switch (type) {
case TYPE_FILE:
if (!file.isFile()) {
return;
}
break;
case TYPE_DIR:
if (!file.isDirectory()) {
return;
}
break;
}
if (match != null && !file.getName().matches(match)) {
return;
}
// If there is a specification whether the specified number of days have passed
if (period != 0) {
// File update date
Date lastModifiedDate = new Date(file.lastModified());
String lastModifiedDateStr = new SimpleDateFormat(“yyyyMMdd”)
.format(lastModifiedDate);
// Specified date (calculated in milliseconds per day)
long oneDayTime = 24L * 60L * 60L * 1000L;
long periodTime = oneDayTime * Math.abs(period);
Date designatedDate =
new Date(System.currentTimeMillis() – periodTime);
String designatedDateStr = new SimpleDateFormat(“yyyyMMdd”)
.format(designatedDate);
if (period > 0) {
if (lastModifiedDateStr.compareTo(designatedDateStr) < 0) {
return;
}
} else {
if (lastModifiedDateStr.compareTo(designatedDateStr) > 0) {
return;
}
}
}
// Store in list if all conditions are met
set.add(file);
}
/** Use TreeSet to sort alphabetically. */
private TreeSet set = new TreeSet();
/**
* If you want to continue using the instance after creating it, use this method.
* Call must be cleared.
* example)
* FileSearch search = new FileSearch();
* File[] f1 = search.listFiles(C:/filelist/”, “*.java”);
* search.clear();
* File[] f2 = search.listFiles(“C:/filelist/”, “*.jsp”);
*/
public void clear(){
set.clear();
}
}
Execution Result
To check the sample program, we created a filelist directory and prepared the following files.
The file name and update date are displayed.
The current date is2007/08/18Suppose it is.
C:\filelist │ aaa.java 2007/08/18 │ bbb.java 2007/08/18 └─dir ccc.java 2007/07/17 ddd.java 2007/08/18 eee.jpg 2007/08/16
◆Example of Execution
System.out.println(“\n●Get all files”);
File[] files = search.listFiles(path, null);
printFileList(files);
search.clear();
System.out.println(“\n●Get file with extension java”);
files = search.listFiles(path, “*.java”);
printFileList(files);
search.clear();
System.out.println(“\n●Get all files and directories”);
files = search.listFiles(path, null,search.TYPE_FILE_OR_DIR, true, 0);
printFileList(files);
search.clear();
System.out.println(“\n●Get files updated within 2 days from the current date”);
files = search.listFiles(path, null,search.TYPE_FILE, true, 2);
printFileList(files);
search.clear();
System.out.println(“\n●Get old files older than 30 days from the current date”);
files = search.listFiles(path, null,search.TYPE_FILE, true, -30);
printFileList(files);
search.clear();
}
private static void printFileList(File[] files) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.println((i + 1) + “: ” + file);
}
}
◆Output result
Retrieve all files 1: C:\filelist\aaa.java 2: C:\filelist\bbb.java 3:C:\filelist\dir\ccc.java 4: C:\filelist\dir\ddd.java 5: C:\filelist\dir\dir\eee.jpg Obtaining a file with the extension java 1: C:\filelist\aaa.java 2: C:\filelist\bbb.java 3: C:\filelist\dir\ccc.java 4: C:\filelist\dir\ddd.java Get all files and directories 1: C:\filelist\aaa.java 2: C:\filelist\bbb.java 3: C:\filelist\dir 4: C:\filelist\dir\ccc.java 5: C:\filelist\dir\ddd.java 6: C:\filelist\dir\dir\eee.jpg Obtaining files that have been updated since two days ago from the current date 1: C:\filelist\aaa.java 2: C:\filelist\bbb.java 3: C:\filelist\dir\ddd.java 4: C:\filelist\dir\dir\eee.jpg Retrieve files older than 30 days from the current date 1: C:\filelist\dir\ccc.java