Directory listing here means a website/web app shows the content of a directory so that user can browse through the content of folders and select the files they want to download. This feature will be handy when list of files for download is high and it gets updated frequently. One simple solution is to enable directory listing feature in web server [Apache setting]. But default listing of server is plain and most of the time it won't match with site's theme. Server site programming is required to accomplish this task. PHP can provide simple and elegant solution, still let us look at J2EE solution for fun. The concept discussed is applicable to both.
We need 3 blocks of code. 1. Server Side Program[SSP] to scan the folders and list files, 2.SSP to generate links to the file & 3. HTML to display the links
1. Server Side Program to scan the folders and list the files
FileAttributesBean class stores 5 attributes of the files namely File name, Size in KB, Last modified date, Last modified date in milli second format and boolean flag to differentiate folders and files. This class also have corresponding getters and setters.
FileOperation class have 2 functions, one to get content of folder and other to sort the content in the required order.generateFileList function scans the folder specified in the parameter and set file attributes in FileAttributesBean object. It returns an ArrayList of FileAttributesBean objects. SortFiles function sorts the arrayList using collections. SortByFileName, SortByLastModified & SortBySize implements comparator function.