Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing only files in directory [closed]

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");
    }
});
like image 350
user1669488 Avatar asked May 06 '13 02:05

user1669488


People also ask

How do I filter only files in Linux?

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 do I list only directories in Linux?

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.

How do I list only files in OS Listdir?

Just use os. listdir and os. path. isfile instead of os.


2 Answers

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();
    }
});
like image 59
MadProgrammer Avatar answered Oct 20 '22 02:10

MadProgrammer


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
    }
}
like image 31
hd1 Avatar answered Oct 20 '22 02:10

hd1