How to List Files in a Folder with PHP & Java

List Files in Folders

In this article I’ll show you How to List the Files that are located in a Directory with PHP & Java. Here are the Source Code Samples and Hints:

PHP

PHP can List the Files in a Directory with two APIs:

  1. Option 1:
$fileList = glob('*'); // place here a file system regex
foreach($fileList as $filename){
    if(is_file($filename) && $filename != 'index.php'){
        echo '<a href="'.$filename.'">' , $filename, '</a>
'; 
    }   
}
  1. Option 2:
$files1 = scandir('.'); // place here some directory that the function will scan.

foreach($files1 as $filename){
    if(is_file($filename) && $filename != 'index.php'){
        echo '<a href="'.$filename.'">' , $filename, '</a>
'; 
    }   
}

In most cases this type of code is probably used in simple cases/places. If you need better code this could be optimized by extracting the “if” statement and converting the echo into template function.

  1. Option 1:
$fileList = glob('*'); // place here a file system regex
foreach($fileList as $filename){
    if(shouldEchoFile($filename)){
        echo echoTemplate($filename); 
    }   
}
  1. Option 2:
$files1 = scandir('.'); // place here some directory that the function will scan.

foreach($files1 as $filename){
  if(shouldEchoFile($filename)){ 
   echo echoTemplate($filename); 
  }   
}
function echoTemplate($filename) {
return is_file($filename) && $filename != 'index.php';
}

function echoTemplate($filename) {
 return '<a href="'.$filename.'">' , $filename, '</a>';
}

The Java API has several variations – https://docs.oracle.com/javase/7/docs/api/java/io/File.html#list() or listFiles or with FilenameFilters or FileFilters – where it returns either the paths as java.lang.String or as a java.io.File. You must always remember that all of them could fail unexpectedly. All methods could:

  • return null – always check if listFiles = null
  • throw some sneaky Security Exception
  • Or fail with IOException. This happens when something spooky is going on with the File Permissions, there is a damaged or corrupted file, or files (and folders) are not found and so on.

The Java API we’ve used in one of our products – File Waiter

Leave a Reply

Your email address will not be published. Required fields are marked *