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.

89  +    =  95