问题
I have a folder with following structure
C:/rootDir/
rootDir has following files
test1.xml
test2.xml
test3.xml
testDirectory <------- This is a subdirectory inside rootDir
I'm only interested in the xml Files inside rootDir. Cuz If I use JDOM to read the XML the following code also considers the files inside "testDirectory" and spits out "content not allowed exception"
File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles();
how can I exclude the subdirectory while using listFiles method? Will the following code work?
File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xml");
}
});
回答1:
Use a FileFilter instead, as it will give you access to the actual file, then include a check for File#isFile
File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return name.endsWith(".xml") && pathname.isFile();
}
});
回答2:
Easier is to realise that the File object has an isDirectory method, which would seem as if it were written to answer this very question:
File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles();
for (File file : files) {
if ( (file.isDirectory() == false) && (file.getAbsolutePath().endsWith(".xml") ) {
// do what you want
}
}
回答3:
File testDirectory = new File("C://rootDir//");
File[] files = testDirectory.listFiles(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xml");
}});
What is the problem with above code. You can use this for listing files by excluding subfolders.
FileFilter also do's same thing but it will be used when file name is not sufficent to listing the files. i.e if you want list all hidden files or readonly file etc. you can use FilteFilter
来源:https://stackoverflow.com/questions/16391367/listing-only-files-in-directory