使用nio.file.DirectoryStream递归列出目录中的所有文件;

我想列出指定目录中的所有文件以及该目录中的子目录。没有目录应列出。


我当前的代码如下。它仅列出指定目录中的文件和目录,因此无法正常工作。


我怎样才能解决这个问题?


final List<Path> files = new ArrayList<>();


Path path = Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");

try

{

  DirectoryStream<Path> stream;

  stream = Files.newDirectoryStream(path);

  for (Path entry : stream)

  {

    files.add(entry);

  }

  stream.close();

}

catch (IOException e)

{

  e.printStackTrace();

}


for (Path entry: files)

{

  System.out.println(entry.toString());

}


繁花如伊
浏览 1069回答 3
3回答

万千封印

Java 8为此提供了一种不错的方法:Files.walk(path)此方法返回Stream<Path>。

慕田峪7331174

制作一个方法,如果下一个元素是目录,该方法将自行调用void listFiles(Path path) throws IOException {&nbsp; &nbsp; try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {&nbsp; &nbsp; &nbsp; &nbsp; for (Path entry : stream) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (Files.isDirectory(entry)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listFiles(entry);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; files.add(entry);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

繁星点点滴滴

检查FileVisitor,非常整洁。&nbsp;Path path= Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");&nbsp;final List<Path> files=new ArrayList<>();&nbsp;try {&nbsp; &nbsp; Files.walkFileTree(path, new SimpleFileVisitor<Path>(){&nbsp; &nbsp; &nbsp;@Override&nbsp; &nbsp; &nbsp;public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!attrs.isDirectory()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;files.add(file);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return FileVisitResult.CONTINUE;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;});&nbsp;} catch (IOException e) {&nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java