Iterate through all files in Java
directory, file, iterator, java, path
Solution
I just tried this and it worked for me. I did have to add one `null` check and changed the directory evaluation method though:
package test;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class Searcher {
public static void main(String[] args) {
ArrayList<File> roots = new ArrayList<File>();
roots.addAll(Arrays.asList(File.listRoots()));
for (File file : roots) {
new Searcher(file.toString().replace('\\', '/')).search();
}
}
private String root;
public Searcher(String root) {
this.root = root;
}
public void search() {
System.out.println(root);
File folder = new File(root);
File[] listOfFiles = folder.listFiles();
if(listOfFiles == null) return; // Added condition check
for (File file : listOfFiles) {
String path = file.getPath().replace('\\', '/');
System.out.println(path);
if (file.isDirectory()) {
new Searcher(path + "/").search();
}
}
}
}
Problem
I want to make my program print huge list of all files that I have on my computer. My problem is that it only prints files from first folder of the first hard-drive, when I want it to print all files located on my computer. Any ideas what am I doing wrong here? Thanks. Here is code I use: Main: ``` import java.io.File; import java.util.ArrayList; import java.util.Arrays; public class Main { public static void main(String[] args) { ArrayList<File> roots = new ArrayList(); roots.addAll(Arrays.asList(File.listRoots())); for (File file : roots) { new Searcher(file.toString().replace('\\', '/')).search(); } } } ``` and Searcher class: ``` import java.io.File; public class Searcher { private String root; public Searcher(String root) { this.root = root; } public void search() { System.out.println(root); File folder = new File(root); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { String path = file.getPath().replace('\\', '/'); System.out.println(path); if (!path.contains(".")) { new Searcher(path + "/").search(); } } } } ```