• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 612
  • Last Modified:

Read directory contents and output in in JSP page

Hi all,

I have several directories of static images and swf files. I want to build a JSP that reads the files, by file type, and renders the images/swf's on the output page. I'd also like to sort by date or file name. Make sense?

I can do this in Perl pretty easily like this:
opendir(IMD, $dirtoget) || die("Cannot open directory");

Then dump into an array:
@thefiles= readdir(IMD);

From there I could output however I wanted. Not sure how to do this in JSP. Help please... :)
1 Solution
Try something like this...

String the_path = "/home/www/site/";
File theDir = new File(the_path);
String[] theDirectoryFiles = theFile.list();

for(int i=0; i<theDirectoryFiles.length; i++) {
    File theFile = new File(thePath + "//" + theDirectoryFiles[i]);
    //this file can then be printed out or whatever.

I had the pieces to this so I put it together. This should give you a start.    rrz

<%@ page import="java.io.*,java.util.*" %>
public class FileComparator implements Comparator{
     public int compare( Object a , Object b ){
       File aFile = new File((String)a);
       File bFile = new File((String)b);
       if(bFile.lastModified() > aFile.lastModified()) return 1;
         else return -1;
    FilenameFilter gifFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".gif");
    FilenameFilter jpgFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jpg");
    //assuming your home directory is in your web app's root directory
    File dir = new File(application.getRealPath("/home/www/site/"));
    String[] gifFiles = dir.list(gifFilter);
    String[] jpgFiles = dir.list(jpgFilter);
    Arrays.sort(gifFiles, new FileComparator());
    Arrays.sort(jpgFiles, new FileComparator());
    for(int i =0; i< gifFiles.length;i++){
                out.print("<img src=\"" + request.getContextPath()
                          + "/home/www/site/" + gifFiles[i] + "\" />");
    for(int i =0; i< jpgFiles.length;i++){
                out.print("<img src=\"" + request.getContextPath()
                          + "/home/www/site/" + jpgFiles[i] + "\" />");
mookie13Author Commented:
This is great!!! I was just now able to get back to this project. Appreciate your help!!

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now