您可以使用 File.listFiles(FileFilter)。请查看以下示例以更好地理解:
package com.stackoverflow.works;
import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;
/*
* @Author: sarath_sivan
*/
public class FileSearchService {
/*
* @Description: Method used to List the files
* @param: directory File, regex String
* @return: fileList File[]
*/
public static File[] search(File directory, String regex) {
if(!directory.isDirectory()) {
throw new IllegalArgumentException(directory+" is no directory.");
}
final Pattern pattern = Pattern.compile(regex); // Caution: could also throw an exception!
return directory.listFiles(new FileFilter(){
@Override
public boolean accept(File file) {
return pattern.matcher(file.getName()).matches();
}
});
}
/*
* @Description: Method used to print the File List
* @param: fileList File[]
* @return: void
*/
public static void printFileList(File[] fileList) {
for (File file : fileList) {
System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("Last Modified: " + getLastModifiedTimestamp(file));
System.out.println();
}
}
/*
* @Description: Method used to get the Last Modified Timestamp
* @param: file File
* @return: void
*/
public static String getLastModifiedTimestamp(File file) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
return sdf.format(file.lastModified());
}
/*
* @Description: Main method used to test the Regex File listing logic
* @param: fileList File[]
* @return: void
*/
public static void main(String[] args) {
String directoryPath = "C:/Users/sarath_sivan/Desktop";
File directory = new File(directoryPath);
String regex = "([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)"; //Regular Expression pattern for image file extension
File[] fileList = search(directory, regex);
printFileList(fileList);
}
}
此代码使用正则表达式列出给定目录中的图像文件。示例输出如下所示: