0

Say I have a particular directory somewhere on my system. C://Users/Public/Local/AppData/saves

I want to read this whole directory and check if the files in it have a particular extension or not. Say .json for example. If the directory has multiple files with the extension .json list all those files with their names.

I could use File file = new File(myPath); and do file.exists() continuously but how can I scan the whole directory for files? Here is what I am confused with.

Any help will be much appreciated. Thanks.

2 Answers2

0

With Java 8, you can use Files.walk

Files.walk(Paths.get("/path/to/folder/"))
.filter(p -> p.toString().endsWith(".json"))
.forEach(x -> System.out.println(x.getFileName()));
0

Old school very readable file name filter:

    File[] jsonFiles=new File("sourcePath").listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File arg0, String name) {
            return name.endsWith(".json");
        }
    });

Or if you want to use lambda stuff: see java 8 lambda expression for FilenameFilter

Conffusion
  • 4,335
  • 2
  • 16
  • 28