简体   繁体   English

如何在Java中仅获取较低级别的子文件夹名称

[英]How to get only the lower level of sub folders name in java

I have the following structure: 我有以下结构:

Main folder
- Folder A
-- Sub Folder AA
--- Sub Folder AAA
----- Files
--- Sub Folder AAB
----- Files
-- Sub Folder AB
--- Sub Folder ABA
---- Sub Folder ABAA
------ Files
--- Sub Folder ABB
------ Files

I would like to get the list of AAA AAB ABAA ABB , the order is not important. 我想获取AAA AAB ABAA ABB的列表,顺序并不重要。

Is there any efficient way to do it? 有什么有效的方法吗?

Iterate through you file list and use Java.io.File.isDirectory() method to check if it is a directory if it is not a directory then it should the previous folder is the least subfolder. 迭代通过你的文件列表,并使用Java.io.File.isDirectory()方法来检查它是否是一个目录,如果它不是一个目录,那么它应该上一个文件夹是最少的子文件夹。

Check http://www.tutorialspoint.com/java/io/file_isdirectory.htm to know the function of Java.io.File.isDirectory() 检查http://www.tutorialspoint.com/java/io/file_isdirectory.htm以了解Java.io.File.isDirectory()的功能

First you should iterate to get all files, after that you can use String's split method for getting the leaves folder. 首先,您应该迭代获取所有文件,然后,可以使用String的split方法获取leaves文件夹。 Sample : 样品:

public MyTest(){
  String str = "c:/a/aa/aaa/test.txt";
  String[] arr = str.split("/");
  System.out.println(arr[arr.length-2]); // print aaa
}

Here is a code snip of what i used: 这是我使用的代码片段:

private void GetListOfFlows(String path, ArrayList<File> files) {
        File directory = new File(path);

        File[] fList = directory.listFiles();
        if(fList.length>0 && !fList[0].isFile())
            for(File x : fList)
                subFolders(x, files);
    }

private void subFolders(File file, ArrayList<File> folders) {

        File[] listFiles = file.listFiles();
        if(listFiles.length > 0 && !listFiles[0].isFile())
            for(File fileInDir : listFiles)
                subFolders(fileInDir, folders);
        else if(listFiles.length > 0 && listFiles[0].isFile())
                folders.add(file);
    }

You could use the java.nio.file-API (link) 您可以使用java.nio.file-API (链接)

(Java >=1.7) (Java> = 1.7)

    List<Path> subDirs = new ArrayList<>();

    Path startPath = Paths.get("your StartPath");
    try {
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                //If there is no subDir --> add it to your list
                if (Files.list(dir).noneMatch(d ->Files.isDirectory(d))){
                    subDirs.add(dir);
                }           
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    //print out all Subdirs
    subDirs.forEach(System.out::println);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM