views:

38

answers:

1

I'm developing a Servlet that should act listing all the files that are on the directory C:\UploadedFiles\CompanyWork on the page and put the link for the files on each one, like this example(using Test.doc as test):

<a href="C:\UploadedFiles\CompanyWork\Test.doc">Test.doc</a>

But I don't know how to do this, I only know how to get the file names and list them(it's a program, but very easy to convert to Servlet):

public static void main(String args[]) {
    File root;
    if (args.length > 0) root = new File(args[0]);
    else root = new File(System.getProperty("user.dir"));
    ls(root); 
}

private static void ls(File f) { 
    File[] list = f.listFiles();
    for (File file : list) {
        if (file.isDirectory()) ls(file);
        else System.out.println(file);
    }
}
+1  A: 

write a simple servlet (follow tutorisl @ http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html). In your doGet() method, write something like below

response.setContentType("text/html");
PrintWriter out = response.getWriter();

File[] list = f.listFiles();
    for (File file : list) {
        if (file.isDirectory()) ls(file);
        else out.println("<a href='+file.toURL()+'>'+file.getName()+'</a>");
    }

you can simplify the listing logic using apache commons-io library

Pangea