java - 使用 java.nio.file* 进行目录和文件扫描;

标签 java path nio

如何在java.io.File中实现相同的功能;

List<File> List = (List<File>) FileUtils.listFilesAndDirs(directory, 
                                    TrueFileFilter.TRUE, TrueFileFilter.TRUE);
String fileID = f.getAbsolutePath().replaceAll(staticRoot, "");

同时重构为 java.nio.file.*;

DirectoryStream<Path> List = Files.newDirectoryStream(Paths.get(directory));    
String fileID = f.??? 

什么方法会返回与 java.io.File 包中相同的输出? 谢谢。

我已经尝试过

String fileID = f.toAbsolutePath().toString().replaceAll(staticRoot, "");

for (Path f : fList) {
    String fileID = f.toAbsolutePath().toString().replaceAll(staticRoot, "");
    System.out.println("file ID : " + fileID);
    String parentID = null;
}

staticRoot =/home/test/dir1/dir10/test9.txt
结果应该剪切 '/home/test/' 并仅返回 dir1/dir10/test9.txt

最佳答案

由于 FileUtils.listFilesAndDirs(directory, TrueFileFilter.TRUE, TrueFileFilter.TRUE) 将递归访问 directory 中的所有子目录,因此您很可能希望将其替换为 Files.walk(Path, FileVisitOption...) 方法.

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

关于java - 使用 java.nio.file* 进行目录和文件扫描;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54091105/

相关文章:

java - JDK7 NIO.2 是否在 Linux 上使用 Epoll 等?

java - 使用 xpath 和 java 解析 xml

java - 如何在 java swing 应用程序中显示 map ?

Java 泛型扩展了涉及枚举的两个类

c# - WPF C# 路径 : How to get from a string with Path Data to Geometry in Code (not in XAML)

http - 如何在 Netty 中读取 HTTP POST 中的消息正文(版本 >= 4.x)

java - 使用 Apache PdfBox 提取两个书签之间的文本

gd库的php路径

java - 无法在 Jetty 中执行特定的 servlet

java - 使用 Java NIO 的高效读/写方法