import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class FileLists { public static void main(String[] args) { String filePath = "/user/data/"; List<String> filePathList = getFileAbsolutePathList(filePath, "13120408.1"); if (!filePathList.isEmpty()) { filePathList.forEach(System.out::println); } } public static List<String> getFileAbsolutePathList(String filePath) { return getFileAbsolutePathList(filePath, null); } /** * 根据文件路径,根据模糊匹配的方法获取特定的文件 */ public static List<String> getFileAbsolutePathList(String filePath, String fileNameLike) { List<String> fileNameList = new ArrayList<>(); File file = new File(filePath); try { if (!file.isDirectory()) { return fileNameList; } // 获取该文件夹下所有文件夹的所有信息 String[] fileList = file.list(); if (fileList == null || fileList.length == 0) { return fileNameList; } for (int i = 0; i < fileList.length; i++) { File readFile = new File(filePath + File.separator + fileList[i]); // 如果当前是文件则添加到list 中 if (readFile.isFile()) { String fileAbsolutePath = readFile.getAbsolutePath(); if (StringUtils.isNotBlank(fileNameLike) && fileAbsolutePath.contains(fileNameLike)) { fileNameList.add(readFile.getAbsolutePath()); continue; } fileNameList.add(readFile.getAbsolutePath()); } } // java8 lambda // fileNameList = Arrays.stream(fileList) // .map(s -> new File((filePath + File.separator + s))) // .filter(File::isFile) // .map(File::getAbsolutePath).collect(Collectors.toList()); } catch (Exception ex) { ex.printStackTrace(); } return fileNameList; } }