0

How to iterate through all files by mask in Java? For example, there's a mask with wild cards like

D:\work\mytestfolder\temp\*.txt 

Need to get a collection (or iterator or whatever else) of all *.txt files in the directory above.

Some more details. Want to process a number of files and it's convenient here to define a set of masks like those shown above. The GLOBE syntax (https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)) looks very helpful and would desirably be supported.

4
  • 3
    what have you already tried? Commented Oct 26, 2017 at 12:41
  • Now struggling with this docs.oracle.com/javase/tutorial/essential/io/find.html. Seems too much complicated for so simple task. Commented Oct 26, 2017 at 12:45
  • @Alex, it's not actually that bad. In Java8 you have Files::walk which streams entities to you. So you split your mask on first wildcard, build a path from first part and a PathMatcher from second part, then start walking from the Path and filter the stream using PathMatcher. Commented Oct 26, 2017 at 12:56
  • have had a look at stackoverflow.com/questions/3057621/…. Not exactly what I need. Of cause we can implement our own solutions but I'd like to find something standard first. Also our hand-made solutions would desirably handle platform specifics, doesn't look like a simple task :( Commented Oct 26, 2017 at 13:13

2 Answers 2

2

No need to create an explicit PathMatcher. Just use Files.newDirectoryStream:

try (DirectoryStream<Path> dir = Files.newDirectoryStream( Paths.get("D:\\work\\mytestfolder\\temp"), "*.txt")) { for (Path entry : dir) { // ... } } 
Sign up to request clarification or add additional context in comments.

3 Comments

It works and is convenient enough, thanks! Just need to get it to iterate also through the subdirectories of the starting directory (recursively).
For recursive traversal, you’ll want Files.walk or Files.walkFileTree. Neither has a file mask option, but obviously it’s easy enough to check each file yourself. The former method returns a Stream, so you can do Files.walk(dir).filter(p -> !Files.isDirectory(p) && p.toString().endsWith(".txt")).
Cannot use Java 8, at least for now. So Files.walkFileTree with explicit PathMatcher seems to be the best choice... though really too verbose :(
0
File dir = new File("E:/Test"); File [] files = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".chm"); } }); for (File xmlfile : files) { System.out.println(xmlfile); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.