How i create a function in JAVA that takes as an argument the name of an operating system folder and returns the number of files in the folder as well as all its subfolders ?
CodePudding user response:
returns the number of files in the folder as well as all its subfolders ?
Its easy to do using the java File API. The methods you are interested in start with the word list
Number of files in a dir
var numFilesInDir = new File(<directory path>).listFiles().length
Getting subdirectory list
File myDir = new File(<directory path>);
String[] myDirSubdirectoryNames = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
Does this solve your problem ? Leave me a comment to tell.
CodePudding user response:
If you are looking to count all files in the directory and all subdirectories you likely need a file tree walker:
long count = Files.walk(startPath)
.filter(p -> !Files.isDirectory(p))
.count();
There are lots of options for what type of files to include in the walk and maximum depth etc. You can also write your own FileVisitor
to do more sophisticated things for each file. See Javadoc https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/nio/file/Files.html for all the details.
One particular thing to be aware of is that the walk leaves directories open until they are closed. The easiest way to ensure this is done is to use a try-with-resources block to ensure the directories are closed even if an exception is thrown.
For example:
try(var walk = Files.walk(Path.of("/mypath"))) {
long count = walk.filter(p -> !Files.isDirectory(p)).count();
...
} catch (IOException | SecurityException e) {
...
}