[英]How to store Java nio files walk() result into a list of String?
我正在使用Java 8,並且具有下面的代碼,其中列出了目錄。
try (Stream<Path> paths = Files.walk(Paths.get("D:/MyDir"))) {
paths.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
我想將結果存儲到List<String>
,如果是目錄,則需要后綴\\
。 我怎樣才能做到這一點?
您的要求並不難:
try (Stream<Path> paths = Files.walk(Paths.get("c:"))) {
List<String> list = paths
.map(path -> Files.isDirectory(path) ? path.toString() + '/' : path.toString())
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
使用Java 8流api,您可以將所有路徑映射到字符串,並像這樣收集所有路徑到列表。
try (Stream<Path> paths = Files.walk(Paths.get("D:\\myDir"))) {
List<String> pathList = paths.map(p -> {
if (Files.isDirectory(p)) {
return "\\" + p.toString();
}
return p.toString();
})
.peek(System.out::println) // write all results in console for debug
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
public static void main(String[] args) throws IOException {
Path path = Paths.get(args[0]);
List<Path> files = Files.walk(path).filter(s -> s.toString().endsWith(".txt")).map(Path::getFileName).sorted()
.collect(Collectors.toList());
for(Path file : files) {
System.out.println("File: " + file);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.