martedì 22 gennaio 2013

Java: List files in a directory/subdirectories

Hello! These are 2 simple functions that sometimes can be useful. So I'll just put both here :) Do you want to list all files in a folder in Java? Here we go!

public void listFilesInFolder(File folder) {
     for (File file : folder.listFiles()) {
          if(!file.isDirectory()){
               System.out.println(file.getName());  
               //or do whatever you want with it
          }
     }
}

The above function will ignore the folders as you can see. So if you want to list also subdirectories files this recursive function is what you need:

public void listFilesInFolderAndSubfolder(File folder) {
     for (File file : folder.listFiles()) {
          if (file.isDirectory()) {
        listFilesInFolderAndSubfolder(file);
          } else {
        System.out.println(file.getName());
        //or do whatever you want with it
   }
     }
}

Use / character for paths as java will understand in windows paths too :) cya soon, Ale

Nessun commento:

Posta un commento