java代码如何列出目录中的所有文件呢?
下文笔者讲述使用java代码打印出目录中所有文件的方法分享,如下所示
打印文件列表的实现思路
输出文件列表的实现思路:
方式1:
使用Files.walk列表
方式2:
使用listFiles方法列出指定文件夹下所有信息
然后依次遍历
例
//输出指定目录下所有文件
try (Stream<Path> walk = Files.walk(Paths.get("D:\\test"))) {
List<String> result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
//输出指定目录下所有文件夹
try (Stream<Path> walk = Files.walk(Paths.get("D:\\test"))) {
List<String> result = walk.filter(Files::isDirectory)
.map(x -> x.toString()).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
//输出所有使用.java结尾的文件
try (Stream<Path> walk = Files.walk(Paths.get("D:\\test"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.endsWith(".java")).collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
//查找文件–testmaomao.java
try (Stream<Path> walk = Files.walk(Paths.get("D:\\test"))) {
List<String> result = walk.map(x -> x.toString())
.filter(f -> f.contains("testmaomao.java"))
.collect(Collectors.toList());
result.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
递归文件搜索功能示例
package com.java265; import java.io.File; import java.util.ArrayList; import java.util.List; public class JavaExample { public static void main(String[] args) { final File folder = new File("D:\\test"); List<String> result = new ArrayList<>(); search(".*\\.java", folder, result); for (String s : result) { System.out.println(s); } } public static void search(final String pattern, final File folder, List<String> result) { for (final File f : folder.listFiles()) { if (f.isDirectory()) { search(pattern, f, result); } if (f.isFile()) { if (f.getName().matches(pattern)) { result.add(f.getAbsolutePath()); } } } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


