I am trying to get the names of all of the text files in a directory. If the directory has subdirectories then I also want to get any text files in those as well. I am not s
The answer is in the tags of your question. Use recursion. Recursion consists in having a method call itself.
In this case, the method should print all the text files directly under a given directory, and call itself for every subdirectory of the directory.
This is a recursive problem
public void find_files(File root)
{
File[] files = root.listFiles();
for (File file : files) {
if (file.isFile()) {
...
} else if (file.isDirectory()) {
find_files(file);
}
}
}
using the java.nio.file capabilites of java 7. I implemented similiar func. and added some test.
Benchmarks when searching for .txt on my PC
"c:/" "c:/windows"
file.io 36272ms 14082ms
file.nio 7167ms 2987ms
Read more in the javadoc, it's quite powerfull API
java.nio.file.filevisitor javadoc
public static void main(String[] args) {
long starttime = System.currentTimeMillis();
try {
Path startPath = Paths.get("c:/");
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
System.out.println("Dir: " + dir.toString());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.toString().endsWith(".txt")){
System.out.println(file.toString());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long completetime = System.currentTimeMillis() - starttime;
System.out.println("totaltime=" + completetime);
}