Java Directory Listing problem
I want to list all the folders of the current directory but there are two problems. Everytime i run this program, the list shows all the files of the last folder inside the directory and the filter does not work.
Can you please help me?
public void foldersPanel()
{
JPanel folderScreen = new JPanel();
folderScreen.setLayout(new GridLayout(1,1));
direFilter = new FilenameFilter()
{
public boolean accept(File file, String string)
{
if (file.isDirectory())
{
return file.isDirect开发者_StackOverflow中文版ory();
}
else
{
return false;
}
}
};
File directory = new File(System.getProperty("user.dir"));
File[] listOfFiles = directory.listFiles(direFilter);
String[] allFiles = directory.list();
if (directory.isDirectory())
{
int x = 1;
for (int i =0; i<listOfFiles.length; i++) // displays all the files
{
if (listOfFiles[i].isDirectory())
{
folderList = new JList(listOfFiles[i].list(direFilter));
System.out.println(x +") Directory = " + listOfFiles[i].getName());
x++;
folderList.setSelectedIndex(1);
}
else
{
System.out.println("is file");
}
folderScreen.add(new JScrollPane(folderList));
}
}
else
{
System.out.println("This is a file, not a directory, so we will move to the parent folder");
directory = directory.getParentFile();
updateLabels();
System.out.println("The new directory is : " +directory.toString());
}
}
code
Your method isn't recursive. A directory is a tree; you want to recursively call a method that adds the list of files to an overall list if it's a directory, or simply add the file if it's a file. Keep accumulating all the lists and you'll have every file under the root directory.
The first parameter of FilenameFilter.accept
is the containing directory. Effectively, your test will always return true
.
[EDIT]
More specifically, I think you really want your test to be:
public boolean accept(File dir, String fileName) {
return new File(dir, fileName).isDirectory();
}
精彩评论