迭代Java中的所有文件 [英] Iterate through all files in Java

查看:180
本文介绍了迭代Java中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的程序打印我的电脑上所有文件的巨大列表。我的问题是,它只打印文件从第一个硬盘驱动器的第一个文件夹,当我想要打印我的电脑上的所有文件。任何想法我在这里做错什么?谢谢。

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.

这里是我使用的代码:

主要:

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();
        }
    }
}

和Searcher类: p>

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();
            }
        }
    }
}


推荐答案

我刚刚尝试过,对我有用。我确实需要添加一个 null 检查并更改目录评估方法:

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();
            }
        }
    }
}

这篇关于迭代Java中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆