gpt4 book ai didi

java - 列出文件名而不显示父路径

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:38:58 25 4
gpt4 key购买 nike

我正在列出给定目录中的所有文件名(递归)。这也包括在子目录中显示文件名。

    File file = new File(FILE_PATH);
// Recursively search for all the resource files.
Collection files = FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (Iterator iterator = files.iterator(); iterator.hasNext();)
{
File fileIter = (File) iterator.next();
System.out.println("File = " + fileIter.getPath());

}

其中File是父目录("C:\Users\sd\Desktop\sdsd)现在上面的代码可以运行文件并列出该目录和子目录中的所有文件,例如

C:\Users\sd\Desktop\sdsd\TagCategory\healthoutcomes_queries\Neurological.txt

但我只想显示(父路径内的路径)

TagCategory\healthoutcomes_queries\Neurological.txt

我该怎么做。

最佳答案

使用 Path.relativize()

Constructs a relative path between this path and a given path.

Relativization is the inverse of resolution. This method attempts to construct a relative path that when resolved against this path, yields a path that locates the same file as the given path. For example, on UNIX, if this path is "/a/b" and the given path is "/a/b/c/d" then the resulting relative path would be "c/d".

所以你只需要通过调用 parentPath.relativize(filePath) 从父路径创建一个相对路径并对每个文件执行此操作:

Path parentPath = Paths.get(FILE_PATH);

for (Iterator<File> iterator = files.iterator(); iterator.hasNext();){
Path filePath = iterator.next().toPath();
Path relativePath = parentPath.relativize(filePath);
System.out.println("File = " + relativePath );
}

请注意,您应该使用通用集合来避免强制转换:Collection<File> ,以及使用“增强的 for 循环”遍历迭代器的现代习语更清晰易读:

for (File file : files) {     
System.out.println("File = " +
parentPath.relativize(file.toPath()));
}

关于java - 列出文件名而不显示父路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com