[java] Getting a list of files in a folder

Started by
6 comments, last by GameDev.net 18 years, 10 months ago
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
Advertisement
try looking at this link:
http://javaalmanac.com/egs/java.io/GetFiles.html

it has a code example of how to list the files and subfolders in the current directoy.
.listFiles()?
Great stuff. I've been wondering about this one myself..
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}

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

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
a.k.a javabeats at yahoo.ca
Quote:File Heros = new File (getDocumentBase ().toString () + "Heros/");

Java coding conventions specify that variable names are camelCase.
Free Mac Mini (I know, I'm a tool)
I think you need to take out the "/" at the end of the name??? I doubt too that
"/" works?

This topic is closed to new replies.

Advertisement