Gleb Gleb - 1 year ago 63
Java Question

a file addition by an incomplete (file) name

I have a method:

public void setup () {
File file = new File(74761_control_*.xml)
//some code

Where * - variable part. Not known in advance how it will exactly be called a file. The program is required to load an xml file with the same name. Is there an elegant way to do this with a standard Java SE API?

Answer Source

The java.nio package has some convencience methods to iterate over directories using a file name pattern:

Path dir = Paths.get("c:\\temp");
Iterator<Path> iterator = Files.newDirectoryStream(dir,  

Now, iterator "holds" all paths that fit to the glob pattern above. The rest is iterator/file handling:

if (!iterator.hasNext()) {
    // file not found
} else {
    Path path =;
    // process file, e.g. read all data
    // or open a reader
    try (BufferedReader reader = Files.newBufferedReader(path)) {
        // process reader

    if (iterator.hasNext()) {
        // more than one file found
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download