Get File Names from Folder

CreateObject
CreateObject used Ask the Experts™
on
This is probably really simple, but I'm an ASP programmer, not a JSP programmer, so I need some help.

I need code to search a specified directory and return the name of all the files in that directory.

Now, in ASP, I would use the FileSystemObject to do this, but I suspect JSP is slightly different.

Here's an idea of what I want to do, shown in ASP code:

<%
  Dim fso
  Set fso = CreateObject("Scripting.FileSystemObject")
     
  Set objFolder = fso.GetFolder(server.MapPath("\myfolder\"))
  Set files = objFolder.files
 
  For Each i in files
%>
     array(i) = <%=i.name%>
     i=i+1
<%
   Next i
%>
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
<%@ page import="java.io.*" %>

<%
  File folder = new File(application.getRealPath("myfolder"));
  File[] files = folder.listFiles();
  for(int j=0;j<files.length;j++){
     out.print(files[j].toString());
  }
%>  

This assumes that "myfolder" is located in your "context" folder.    

Commented:
this is a class that returns the content of a directory...

import java.io.*;
import java.util.*;

public class DirList {

Vector dirList = new Vector();

public String[] getDirList(String path)
{
File f1 = new File(path);
String s[] = f1.list(filtro);
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
return s;
}


public Vector dirIntoVector(String[] s)
{

for(int i=0;i<s.length;i++)
{
dirList.addElement(s[i]);
}
return dirList;
}

}



*****************************************
in the jsp you write this

DirList directoryList = new DirList();
 String[] dirList = directoryList.getDirList("your path");
 Vector dirListVector = directoryList.dirIntoVector(dirList);
 for(int i=0;i<dirListVector.size();i++)
 {out.println(dirListVector.get(i));}

i hope this resolve your problem

Commented:
Wow,evedder and I posted the exact same time.
We used two differant File methods. I used listFiles() which returns an array of File objects and when printed give the complete path.  evedder uses  list() which will return an array of String objects containing the name of the files(which is what you asked for).

Author

Commented:
Since yours was the first answer to appear, and since it was more concise, I'll award you the points.

I did have to do some tinkering with your code, however, because it's printing the full path to the file, not just the file name.

Bummer.

Thanks.

--CO

Commented:
use list() instead of listFiles()
thanks for the points

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial