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.
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()));
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.