Java: Find first file in the directory and return its name

Task: Search files by mask and return first name

Implementation:

       String licenseFileName = null;
       try ( DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get("."), "file*.ext")) {
           Iterator<Path> fileIterator = ds.iterator();
           if (fileIterator.hasNext()) {
               licenseFileName = fileIterator.next().getFileName().toString();
           }
       } catch (IOException ex) {
           System.err.println("Error...");
       }
       System.out.println("Filename: " + licenseFileName);

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *

  +  20  =  24

Skynin cache:
Array ( [cache mode] => capture [requestKey] => 1053a55f21e225183b61114e650b70a69af.sc [skycache_disable_capture] => false )