Created
January 23, 2020 11:06
-
-
Save julianjupiter/08edd8ff27704d3815a4cbc91afebcc6 to your computer and use it in GitHub Desktop.
Searching for file with filename pattern and location as parameters.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.IOException; | |
| import java.nio.file.FileSystems; | |
| import java.nio.file.Files; | |
| import java.nio.file.Path; | |
| import java.nio.file.PathMatcher; | |
| import java.nio.file.Paths; | |
| import java.util.Optional; | |
| public class FileFinder { | |
| public static void main(String[] args) throws IOException { | |
| Optional<Path> pathOptional = findFile("hello_*.txt", Paths.get("C:/opt/workspace/files")); | |
| if (pathOptional.isPresent()) { | |
| Path path = pathOptional.get(); | |
| System.out.println(path.toFile().getAbsolutePath()); | |
| } | |
| } | |
| public static Optional<Path> findFile(String globPattern, Path location) throws IOException { | |
| PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + globPattern); | |
| return Files.walk(location).filter(path -> { | |
| System.out.println(path.toFile().getAbsolutePath()); | |
| return pathMatcher.matches(path.getFileName()); | |
| }).findFirst(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment