即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

递归地列出所有文件在一个目录使用nio.file.directorystream;

栈溢出 Danny Rancher 46℃ 0评论
本文目录
[隐藏]

1.原始问题:Recursively list all files within a directory using nio.file.DirectoryStream;

I want to list all the FILES within the specified directory and subdirectories within that directory. No directories should be listed.

My current code is below. It does not work properly as it only lists the files and directories within the specified directory.

How can I fix this?

final List files = new ArrayList<>();

Path path = Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");
try
{
  DirectoryStream 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());
}

Regards.

2.被采纳答案

暂无被采纳答案,请参照下面其他答案。

3.其他高票答案

3.1.第1个答案

Make a method which will call itself if a next element is directory

void listFiles(Path path) throws IOException {
    try (DirectoryStream stream = Files.newDirectoryStream(path)) {
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
                listFiles(entry);
            }
            files.add(entry);
        }
    }
}

3.2.第2个答案

Check FileVisitor, very neat.

 Path path= Paths.get("C:\\Users\\Danny\\Documents\\workspace\\Test\\bin\\SomeFiles");
 final List files=new ArrayList<>();
 try {
    Files.walkFileTree(path, new SimpleFileVisitor(){
     @Override
     public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
          if(!attrs.isDirectory()){
               files.add(file);
          }
          return FileVisitResult.CONTINUE;
      }
     });
 } catch (IOException e) {
      e.printStackTrace();
 }

3.3.第3个答案

Java 8 provides a nice way for that:

Files.walk(path)

This method returns Stream.

3.4.第4个答案

If you want to avoid having the function calling itself recursively and having a file list that is a member variable, you can use a stack:

private List listFiles(Path path) throws IOException {
    Deque stack = new ArrayDeque();
    final List files = new LinkedList<>();

    stack.push(path);

    while (!stack.isEmpty()) {
        DirectoryStream stream = Files.newDirectoryStream(stack.pop());
        for (Path entry : stream) {
            if (Files.isDirectory(entry)) {
                stack.push(entry);
            }
            else {
                files.add(entry);
            }
        }
        stream.close();
    }

    return files;
}

转载请注明:CodingBlog » 递归地列出所有文件在一个目录使用nio.file.directorystream;

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情