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.Is中搜索特定的子目录吗?
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
的目录答案 0 :(得分:1)
使用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;
}
}
答案 1 :(得分:0)
您可以使用File.listFiles()
方法
public Collection<File> findDir(File dir, String name) {
ArrayList<File> result = new ArrayList<File>();
if(!dir.isDirectory()) return result;
for(File child : dir.listFiles()) {
if(child.getName().equals(name)) result.add(child);
result.addAll(findDir(child, name));
}
return result;
}
假设您要查找z1
内的所有C:\projects\workspace\testing
目录,请:
Collection<File> result = findDir(new File("C:/projects/workspace/testing"), "z1");