读取指定后缀文件名为List返回
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
public static List<String> getFileNamesBySuffix(String directoryPath, String fileSuffix) {
List<String> fileNames = new ArrayList<>();
if (directoryPath == null || fileSuffix == null) {
throw new IllegalArgumentException("目录路径或文件后缀不能为空");
}
File directory = new File(directoryPath);
if (!directory.exists() || !directory.isDirectory()) {
throw new IllegalArgumentException("指定路径不是有效的目录");
}
File[] files = directory.listFiles((dir, name) -> name.endsWith(fileSuffix));
if (files != null) {
for (File file : files) {
if (file.isFile()) {
fileNames.add(file.getName());
}
}
}
return fileNames;
}
public static void main(String[] args) {
String directoryPath = "./test_directory";
String fileSuffix = ".txt";
try {
List<String> fileNames = getFileNamesBySuffix(directoryPath, fileSuffix);
System.out.println("符合条件的文件名:");
for (String fileName : fileNames) {
System.out.println(fileName);
}
} catch (IllegalArgumentException e) {
System.err.println("错误: " + e.getMessage());
}
}
}