Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Created January 23, 2020 11:06
Show Gist options
  • Select an option

  • Save julianjupiter/08edd8ff27704d3815a4cbc91afebcc6 to your computer and use it in GitHub Desktop.

Select an option

Save julianjupiter/08edd8ff27704d3815a4cbc91afebcc6 to your computer and use it in GitHub Desktop.
Searching for file with filename pattern and location as parameters.
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