read file system structure from java

2019-08-05 04:20发布

Is it possible to read all the names of folders (not sub-folders) inside a directory and save the list in an ArrayList, etc ?

e.g- if a directory has the following folders inside it- CLIENT1, CLIENT2, CLIENT3, etc. I want the ArrayList to be something like this- [CLIENT1, CLIENT2, CLIENT3, etc].

The folders are in an unix server, so either java code or a shell script(bash/tcsh/etc) or their combination would do.

3条回答
狗以群分
2楼-- · 2019-08-05 04:38

This would feel slightly cleaner to me than a blunt iteration constructing new File() each time.

public class DirFilter implements FileFilter {
    public static FileFilter INSTANCE = new DirFilter();
    @Override
    public boolean accept(File file) {
        return file.isDirectory();
    }
}

File startDir = .....;
List<File> children = Arrays.asList(startDir.listFiles(DirFilter.INSTANCE));
查看更多
迷人小祖宗
3楼-- · 2019-08-05 04:40

The below Java code snippet should help you. It will return the list of all folders within a directory.It may return an empty list based on the manner in which you deal with any possible IO exception.

public List<String> getDirectoriesInFolder(String folderPath)
{
     List<String> folderNames = new ArrayList<String>();
     try
     {
         File directory = new File (folderPath);
         String[] allFilesInFolder = directory.list();
         for(String fileName : allFilesInFolder)
         {
            File f = new File(fileName);
            if(f.isDirectory)
            {
               folderNames.add(fileName);
            } 

         }

     }
     catch(IOException iex)
     {
          //Do any exception handling here...
     }
     return folderNames; 
}

If you want to do it using Shell scripting then the guidance provided on the below links should help you come to a solution:

help with script to list directories

bash: put output from ls into an array

查看更多
做个烂人
4楼-- · 2019-08-05 04:41

Try this:

File dir = new File("directoryName");
File temp;
String[] children = dir.list();
if (children !=null) {
    for (int i=0; i<children.length; i++) {
        temp = new File(children[i]);
        if(temp.isDirectory()) //add children[i] to arrayList
    }
}
查看更多
登录 后发表回答