Java 递归列出特定模式目录中的文件
Java recursively list the files from directory of specific pattern
我在 directory/file 结构下面
ABC
-- Apps
-- Tests
-- file1.xml
-- file2.xml
-- AggTests
-- UnitTests
PQR
-- Apps
-- Tests
-- file3.xml
-- file4.xml
-- AggTests
-- UnitTests
这里我只想获取 Tests
目录中的文件列表。我怎样才能在 java 中实现它,我发现这很有帮助
下面列出了所有 XML 文件,但我需要来自名为 Tests
?
的特定目录
try (Stream<Path> walk = Files.walk(Paths.get("C:\projects"))) {
List<String> fileList = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
fileList.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
最终,我需要fileList = [file1.xml, file2.xml, file3.xml, file4.xml]
List<String> fileList = walk.filter(x -> x.getParent().endsWith("Tests")).map(x -> x.toString())
.filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
如果你只需要文件名,而不需要整个路径,你可以这样做:
List<String> fileList = walk.filter(x -> x.getParent().endsWith("Tests")).map(x -> x.getFileName().toString())
.filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
public List<String> getAllFiles(String baseDirectory,String filesParentDirectory) throws IOException{
return Files.walk(Paths.get(baseDirectory))
.filter(Files::isRegularFile)
.filter(x->(x.getParent().getFileName().toString().equals(filesParentDirectory)))
.map(x->x.getFileName().toString()).collect(Collectors.toList());
}
我在 directory/file 结构下面
ABC
-- Apps
-- Tests
-- file1.xml
-- file2.xml
-- AggTests
-- UnitTests
PQR
-- Apps
-- Tests
-- file3.xml
-- file4.xml
-- AggTests
-- UnitTests
这里我只想获取 Tests
目录中的文件列表。我怎样才能在 java 中实现它,我发现这很有帮助
下面列出了所有 XML 文件,但我需要来自名为 Tests
?
try (Stream<Path> walk = Files.walk(Paths.get("C:\projects"))) {
List<String> fileList = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
fileList.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
最终,我需要fileList = [file1.xml, file2.xml, file3.xml, file4.xml]
List<String> fileList = walk.filter(x -> x.getParent().endsWith("Tests")).map(x -> x.toString())
.filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
如果你只需要文件名,而不需要整个路径,你可以这样做:
List<String> fileList = walk.filter(x -> x.getParent().endsWith("Tests")).map(x -> x.getFileName().toString())
.filter(f -> f.endsWith(".xml")).collect(Collectors.toList());
public List<String> getAllFiles(String baseDirectory,String filesParentDirectory) throws IOException{
return Files.walk(Paths.get(baseDirectory))
.filter(Files::isRegularFile)
.filter(x->(x.getParent().getFileName().toString().equals(filesParentDirectory)))
.map(x->x.getFileName().toString()).collect(Collectors.toList());
}