迭代Java中的所有文件

Roh*_*ish 3 java directory iterator file path

我想让我的程序打印出我计算机上所有文件的巨大列表.我的问题是它只打印第一个硬盘驱动器的第一个文件夹中的文件,当我想要它打印我的计算机上的所有文件.我有什么想法在这里做错了吗?谢谢.

这是我使用的代码:

主要:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和Searcher课程:

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

mpr*_*vat 6

我刚试过这个,它对我有用.我确实必须添加一个null检查并更改了目录评估方法:

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)