Question

I have a directory with multiple files. I need to retrieve only XML file names in a List using Java. How can I accomplish this?

Was it helpful?

Solution

Try this, {FilePath} is directory path:

public static void main(String[] args) {
    File folder = new File("{FilePath}");
    File[] listOfFiles = folder.listFiles();
    for(int i = 0; i < listOfFiles.length; i++){
        String filename = listOfFiles[i].getName();
        if(filename.endsWith(".xml")||filename.endsWith(".XML")) {
            System.out.println(filename);
        }
    }
}

OTHER TIPS

You can use also a FilenameFilter:

import java.io.File;
import java.io.FilenameFilter;

public class FileDemo implements FilenameFilter {
    String str;

    // constructor takes string argument
    public FileDemo(String ext) {
        str = "." + ext;
    }

    // main method
    public static void main(String[] args) {

        File f = null;
        String[] paths;

        try {
            // create new file
            f = new File("c:/test");

            // create new filter
            FilenameFilter filter = new FileDemo("xml");

            // array of files and directory
            paths = f.list(filter);

            // for each name in the path array
            for (String path : paths) {
                // prints filename and directory name
                System.out.println(path);
            }
        } catch (Exception e) {
            // if any error occurs
            e.printStackTrace();
        }
    }

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(str.toLowerCase());
    }
}

You can filter by using File.filter(FileNameFilter). Provide your implementation for FileNameFilter

File f = new File("C:\\");
if (f.isDirectory()){
   FilenameFilter filter =  new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if(name.endsWith(".xml")){
                    return true;
                }
                return false;
            }
        };
   if (f.list(filter).length > 0){
      /* Do Something */
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top