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 because 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 the 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");
}
});
Open the command-line shell and write the 'ls” command to list only directories. The output will show only the directories but not the files. To show the list of all files and folders in a Linux system, try the “ls” command along with the flag '-a” as shown below.
How can I list directories only in Linux? Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only.
Just use os. listdir and os. path. isfile instead of os.
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();
}
});
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With