gpt4 book ai didi

java - 如何从父目录中查找子目录?

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:35 27 4
gpt4 key购买 nike

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

public class DirectoryContents
{

public static void main(String[] args) throws IOException
{

File f = new File(".");
FileFilter directoryFilter = new FileFilter()
{
public boolean accept(File file)
{
return file.isDirectory();
}
};

File[] files = f.listFiles(directoryFilter);
for (File file : files)
{
if (file.isDirectory())
{
System.out.print("directory:");
}
else
{
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}

}

}

我可以列出父目录中的所有子目录。但我想在java中搜索特定的子目录。有什么办法吗?

directory:C:\projects\workspace\testing

如何仅列出子目录(z1)而不列出文件? (子目录z1存在于各个子目录中)

directory:C:\projects\workspace\testing\z1
directory:C:\projects\workspace\testing\f5\z1
directory:C:\projects\workspace\testing\f5\a\g\h\d

输出应该是包含 z1 的目录

最佳答案

使用Files.walkFileTree,它会递归地显示您的父目录对应的子目录。

public static void main(String[] args) throws IOException {
Path startingDir = Paths
.get("C:\\projects\\workspace\testing");
Files.walkFileTree(startingDir, new FindJavaVisitor());
}

private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) throws IOException {
if(dir.getFileName().toAbsolutePath().toString().contains("z1")){
System.out.println("z1 is found at"+ dir.getFileName().toAbsolutePath());
}
return FileVisitResult.CONTINUE;
}
}

关于java - 如何从父目录中查找子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20438328/

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