My linux server has a directory that contains many other sub-directories, that contains files named with keywords. For example:
Dir1:
-Dir1.1:
-file-keyword11-keyword7-keyword9.txt
-file-keyword2-keyword7-keyword97.txt
-Dir1.2:
-file-keyword4-keyword6-keyword9.txt
-file-keyword2-keyword8-keyword3.txt
Dir2:
-Dir2.1:
-file-keyword5-keyword42-keyword2.txt
-file-keyword8-keyword11-keyword9.txt
I need a to create a method that returns a list of all files containing one of two keywords. For example:
findFiles("keyword11", "keyword42");
Should return the following files of the previous example:
-file-keyword11-keyword7-keyword9.txt
-file-keyword5-keyword42-keyword2.txt
-file-keyword8-keyword11-keyword9.txt
I am thinking about creating a recursive method that tests if the name of each file contains one of the two keywords. But I am afraid about performance, because the directories have thousands of files and sub-directories. And there will be more and more files that will be created every day.
I would like to know what would be the right way to do it. Should I use file.getName().contains()
method? Should I use regex? Or should I use a linux command like grep?
You can use FileVisitor, it's very convenient.
Here is the example:
If you want to do smth with directories, use
preVisitDirectory
andpostVisitDirectory
methods to do smth before and after you visit a directory.