USer22999299
USer22999299

Reputation: 5684

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.

Is there any efficient way to do it?

Upvotes: 0

Views: 1829

Answers (4)

griFlo
griFlo

Reputation: 2164

You could use the java.nio.file-API (link)

(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);

Upvotes: 0

USer22999299
USer22999299

Reputation: 5684

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);
    }

Upvotes: 0

Rudy
Rudy

Reputation: 7044

First you should iterate to get all files, after that you can use String's split method for getting the leaves folder. Sample :

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

Upvotes: 1

Sam
Sam

Reputation: 1328

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.

Check http://www.tutorialspoint.com/java/io/file_isdirectory.htm to know the function of Java.io.File.isDirectory()

Upvotes: 2

Related Questions