查找文件夹列表中的最后一个文件夹

时间:2016-03-18 11:51:56

标签: java file

有没有更快的方法来查找里面没有其他文件夹的文件夹?

File dir = new File("C:\\Users\\axs0552\\Desktop\\barcode\\");
File[] cartella = dir.listFiles();

List<String> Nome_cartela = null;
if (cartella == null) {
    logger.debug("ERRORE: cartella inesistente, oppure directoy errata !!");
} else {
    for (int i = 0; i < cartella.length; i++) {
        if (cartella[i].isDirectory()) {
            System.out.println("cartella radice n° :" + i + " " + cartella[i].getName());
            File[] figli = cartella[i].listFiles();
            for (int j = 0; i < figli.length; i++) {
                if (figli[i].isDirectory()) {
                    System.out.println("cartella figlio n° :" + j + " " + figli[i].getName());
                }
            }
        }
    }
}

6 个答案:

答案 0 :(得分:2)

如果要递归检查我建议使用FileVisitor的所有目录。这是一个简单的例子,只输出进入和离开的所有名称并计算目录:

public class MyFileVisitor implements FileVisitor<Path> {
    private int dirCount = 0;

    @Override
    public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes bfa) throws IOException {
        System.out.println("Entering directory: " + path);
        dirCount++;
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path path, IOException ex) throws IOException {
        System.out.println("Leaving directory: " + path);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes bfa) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path path, IOException ex) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    public int getDirCount() {
        return dirCount;
    }

}

main可能看起来像这样:

public class Main {

    public static void main(String[] args) {
        Path path = Paths.get("c:/users");
        MyFileVisitor fileVisitor = new MyFileVisitor();
        try {
            Files.walkFileTree(path, fileVisitor);
            System.out.println(fileVisitor.getDirCount() + " directories");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

答案 1 :(得分:2)

如果您只想从脚本中获取逻辑,则可以像这样编写它(请注意,为了简单起见,findFolderWihtoutSubfolders是静态的):

package tests;

import java.io.File;

public class Directories {

    public static File findFolderWithoutSubfolders(File dir) {
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                boolean flag = true;
                for (File ff : f.listFiles()) {
                    if (ff.isDirectory()) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    return f;
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        File f = findFolderWithoutSubfolders(new File("C:\\Users\\stack\\test"));
        if (f != null) {
            System.out.println("Folder is : " + f.getName());
        } else {
            System.out.println("no folder found");
        }
    }
}

答案 2 :(得分:1)

该方法不是递归的。只检查两个级别。使用file tree walking from nio2

实现树浏览
import java.io.File;
import java.io.FileFilter;

// yet another file util class
public class YAFU {

    public static void main(String[] args) {

        File[] simpleFolders = YAFU.simpleFolders(new File("/tmp"));

        if (simpleFolders == null)
            System.out.println("nothing found");
        else
            for (File f : simpleFolders) {
                System.out.println(f.getName());
            }

    }

    public static boolean containsDirectories(File file) {
        if (file == null || !file.isDirectory()) {
            return false;
        } else {
            File[] found = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return file.isDirectory();
                }
            });
            return (found == null) ? false : found.length > 0;

        }

    }

    public static File[] simpleFolders(File rootDir) {
        if (rootDir == null || !rootDir.isDirectory()) {
            return null;
        } else {
            return rootDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return containsDirectories(file);
                }
            });
        }

    }

}

答案 3 :(得分:1)

打印根目录下所有空目录的简单方法可以是以下代码段。

假设以下结构(文件名为source = self._tree_read(src, tree_path)

for s in source['servers']:
    try:
        subprocess.call(["/bin/bash", "./servers.sh",
                         s["server"],
                         s["hostname"],
                         s["url"],
                       **s["users"]**
                        ], shell=False)

摘录

*.file

输出

/tmp/foo
/tmp/foo/bar
/tmp/foo/bar/bar.file
/tmp/foo/bar/barfoo
/tmp/foo/bar/foobar
/tmp/foo/bar/foobar/foobar.file
/tmp/foo/bar.file
/tmp/foo/baz

不打印以下目录

Path rootPath = Paths.get("/tmp/foo");
Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
        .map(Path::toFile)
        .filter((file) -> file.isDirectory() && file.listFiles().length == 0)
        .forEach(System.out::println);

答案 4 :(得分:0)

您可以执行以下操作

public class LastFolderFinder {
public static void main(final String[] args){
    final Path dir = Paths.get("C:\\Users\\axs0552\\Desktop\\barcode\\");
    visitDir(dir);
}

private static void visitDir(final Path dir) {
    try (final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir, new DirectoryFilter());) {
        final Iterator<Path> iterator = directoryStream.iterator();
        if (iterator.hasNext()) {
            while (iterator.hasNext()) {
                final Path next = iterator.next();
                visitDir(next);
            }
        } else {
            System.out.println("last directory: " + dir);
        }
    } catch (final Exception exception) {
        exception.printStackTrace();
    }
}
}

class DirectoryFilter implements Filter<Path> {
    @Override
    public boolean accept(final Path entry) throws IOException {
        return entry.toFile().isDirectory();
    }
}

答案 5 :(得分:0)

或者您可以按照更新的https://stackoverflow.com/a/36084399/3333885进行更新

public class LastFolderFinder {
    public static void main(final String[] args) throws IOException {
        final Path dir = Paths.get("C:\\Users\\axs0552\\Desktop\\barcode\\");

        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(final Path path, final BasicFileAttributes bfa) throws IOException {
                if (hasDirectories(path)) {
                    return FileVisitResult.CONTINUE;
                }
                System.err.println(path);
                return FileVisitResult.SKIP_SUBTREE;
            }

            @Override
            public FileVisitResult postVisitDirectory(final Path path, final IOException ex) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes bfa) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });

    }

    private static boolean hasDirectories(final Path dir) {
        try (final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir, new DirectoryFilter());) {
            final Iterator<Path> iterator = directoryStream.iterator();
            return iterator.hasNext();
        } catch (final Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

}

class DirectoryFilter implements Filter<Path> {

    @Override
    public boolean accept(final Path entry) throws IOException {
        return entry.toFile().isDirectory();
    }

}