• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to only list sub directories in JList?  RSS feed

 
Frank John
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to list only the sub directories of a specific directory, not including files. I used the following code, but files in the "mall" directory also are included.
File mallDir = new File("mall");
if(!mallDir.exists()){System.out.println(mallDir.getName() + " not found."); return;}
if (mallDir.isDirectory()){String[] store = mallDir.list();}
JList list1 = new JList(store);
JScrollPane storeList = new JScrollPane(list1);
Any suggetion? Thanks
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Frank,
Well, you're just going to have to thru and check each file in the list to see if it is also a directory. Something like this:

Hope this helps,
Michael Morris
 
Frank John
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Michael. Your code is much better than the one I used string array in beginner's forum. Sorry for the double post.
By the way, maulin. Your code on the beginner's forum doesn't work. list() method can't have FileFilter arguement. Maybe filter is not the way to go.
Thank you guys.
 
Frank John
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, maulin. I tried again with FileFilter. It worked well with the return type of File[]. The only thing I need to do is change File[] to String[]. I can only use a "for loop" to do it, as follows:
import java.io.*;
class MyFileFilter implements FileFilter {
public boolean accept(File f) {
return f.isDirectory();
}}
public class Test {
public static void main(String[] s) {
File f = new File("c:" + File.separator);
File[] list = f.listFiles(new MyFileFilter());
String[] list2 = new String[list.length];
for(int i=0; i<list.length; i++){
list2[i] = list[i].getName();
System.out.println(list2[i]);
}
}
}
Are there any better way to change File[] to String[] directly?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!