-1

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?

Gleb
  • 13
  • 3
  • There is no guarantee that your pattern does not match multiple files. So no, this does not work. – isnot2bad Oct 28 '16 at 07:26
  • @isnot2bad I guarantee that this pattern will have only one file. – Gleb Oct 28 '16 at 07:27
  • Yes, you guarantee for yourself, but as you can't guarantee for the rest of the world, there is no direct java API that allows you to use a pattern to construct a `File` object, as a `File` object always references one single file or directory. But see my answer below, there is another, not much more complex way to do what you want. – isnot2bad Oct 28 '16 at 07:44
  • Plenty of resources if you google for *java open file wildcard* – Scary Wombat Oct 28 '16 at 07:47

1 Answers1

0

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
    }
}
isnot2bad
  • 24,105
  • 2
  • 29
  • 50