Search directory for any .XML file
Asked Answered
L

6

2

I am trying to get a piece of code working. The aim is to check if there is an .XML file in a certain directory.

This is what I've got so far.

File f = new File("saves/*.xml");

    if(f.exists()) {
        /* Do Something */
    } else {
        /* do something else */
    }

I'm trying to use a wildcard to search for any file ending in .XML, am I missing something simple here? Is there an easier way to check that at least one .XML file exists in a specified directory?

thanks in advance.

Lys answered 22/4, 2013 at 9:20 Comment(4)
better try checking whether the f is NULL or not... tried ??Tum
@HirenPandya f won't be null, it's assigned to new File("saves/*.xml"); just one line above. This doesn't mean the file exists, but f won't be null.Zoan
@jlordo.. Let me take it as a file object. If the mentioned directory doesn't contain any file specified. Then f should be containing null... Am I wrong somewhere ..?Tum
@HirenPandya yes, you are wrong. f references a File object, not null. Whether the file denoted by the abstract path name stored in that object exists is a whole other question. Just run following code: File f = new File("DOESNOTEXIST"); if (f != null) {System.out.println("f is not null");}Zoan
Z
9

You can use this:

    File dir = new File("saves");
    if (dir.isDirectory()) {
        File[] xmlFiles = dir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File folder, String name) {
                return name.toLowerCase().endsWith(".xml");
            }
        });
    }

Now all of your xml files are in the File[] xmlFiles.

Zoan answered 22/4, 2013 at 9:27 Comment(0)
P
3

Alternative 1:

You can use PathMatcher to search for files using specific pattern.

Alternative 2:

You can also use listFiles(FilenameFilter filter)

Phocomelia answered 22/4, 2013 at 9:24 Comment(0)
A
1

You need to use a PathMatcher, something like:

PathMatcher matcher =
    FileSystems.getDefault().getPathMatcher("glob:*.{xml}");

Path filename = ...;
if (matcher.matches(filename)) {
    System.out.println(filename);
}

From the Oracle documentation here. And if you are wondering what a Glob is: here it is explained.

Attah answered 22/4, 2013 at 9:27 Comment(0)
G
1

Separate the filter part from the search path and list the files in the search path with a file name filter, filtering only the xml files. If the list sizee is greater than 0 then you know that the search path contains atleast one xml file. See sample code below:

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 */
   }
}
Godoy answered 22/4, 2013 at 9:41 Comment(0)
T
0

You can try using this code for your reference...

import java.io.*;

public class FindCertainExtension {

private static final String FILE_DIR = "FOLDER_PATH";
private static final String FILE_TEXT_EXT = ".xml";

public static void main(String args[]) {
    new FindCertainExtension().listFile(FILE_DIR, FILE_TEXT_EXT);
}

public void listFile(String folder, String ext) {

    GenericExtFilter filter = new GenericExtFilter(ext);

    File dir = new File(folder);

    if(dir.isDirectory()==false){
        System.out.println("Directory does not exists : " + FILE_DIR);
        return;
    }

    // list out all the file name and filter by the extension
    String[] list = dir.list(filter);

    if (list.length == 0) {
        System.out.println("no files end with : " + ext);
        return;
    }

    for (String file : list) {
        String temp = new StringBuffer(FILE_DIR).append(File.separator)
                .append(file).toString();
        System.out.println("file : " + temp);
    }
}

// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {

    private String ext;

    public GenericExtFilter(String ext) {
        this.ext = ext;
    }

    public boolean accept(File dir, String name) {
        return (name.endsWith(ext));
    }
}
}

Hope it helps..

Tum answered 22/4, 2013 at 9:29 Comment(0)
M
0

The simplest code I could come up:

File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));

Then you can check if there are any xml files like that:

if(files.length == 0) {
    /* Do Something */
} else {
    /* do something else */
}
Martyrize answered 24/10, 2019 at 0:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.