Sign in to follow this  
jake_Ghost

[java] Getting a list of files in a folder

Recommended Posts

I have been unsuccessful on getting a list of file from a folder. At this point I have been using...
File Heros = new File (getDocumentBase ().toString () + "Heros/");

        HeroName = Heros.list ();

but this doesn't work because all the slots in the HeroName array are null. Does anyone know how to do this? Jake

Share this post


Link to post
Share on other sites
it amazes me the number of people that don't read the API documentation
java.io.File.
Quote:

list
public String[] list()Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of strings is returned, one for each file or directory in the directory. Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path.

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.


Returns:
An array of strings naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Throws:
SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the directory

the bold portion is your problem


here's how to do it.

try{
File f = new File ("mypathstring");
File[] files;
if(f.isDirectory()){
files = f.listFiles(); //There is an optional FileFilter parameter to list files that meet a certain criteria
//do some stuff to the files
}
}
catch(NullPointerException e){
//if the pathname argument is null
}

Share this post


Link to post
Share on other sites
Quote:
it amazes me the number of people that don't read the API documentation


Yes, a sad reality on these forums. =/

Jake, don't forget to implement your own FileFilter classes if you wish to filter the files returned by the listFiles() method.

Son Of Cain

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
I think you need to take out the "/" at the end of the name??? I doubt too that
"/" works?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this