Gleb Gleb - 1 month ago 10
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

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,  
                                    "74761_control_*.xml").iterator();

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 = iterator.next();
    // process file, e.g. read all data
    Files.readAllBytes(path);
    // or open a reader
    try (BufferedReader reader = Files.newBufferedReader(path)) {
        // process reader
    }

    if (iterator.hasNext()) {
        // more than one file found
    }
}
Comments