首页 > 解决方案 > 如何使用java多线程扫描多个目录

问题描述

问题陈述是,您必须列出给定目录中文件的名称,您已经给出了一个目录结构,其中包含一些子目录和一些文件。

我做了一些代码,但它不工作,你能帮我什么是正确的做法。

代码

public class Test {
public static void main(String[] args) {
    RunableExample run = new RunableExample();
    Thread th = new Thread(run, "thread1");
    String directoryName = "C:\\Users\\GUR35893\\Desktop\\CleanupMTM";
    File directory = new File(directoryName);
    File[] fList = directory.listFiles();
    RunableExample.MyList = new ArrayList<File>();
    for (File file : fList) {
        RunableExample.MyList.add(file);
    }
    try {
        th.start();
    } catch (Exception e) {

    }
  }
 }

 public class RunableExample implements Runnable {
public static List<File> MyList;
int count = 0;
File filepath;

public void run() {
    try {
        while (count < MyList.size()) {
            System.out.println(Thread.currentThread().getName() + ">>>>"
                    + MyList.size() + " >>>>> " + count);
            filepath = MyList.get(count);

            if (filepath != null && filepath.isFile()) {

                System.out.println(Thread.currentThread().getName() + " >>"
                        + filepath.getAbsolutePath());
            } else {
                synchronized (this) {
                    if (filepath != null) {
                        // System.out.println("Else");
                        RunableExample run3 = new RunableExample();
                        Thread th3 = new Thread(run3, "thread" + count);
                        File[] fList = filepath.listFiles();
                        // System.out.println("Else1");
                        for (File file : fList) {
                            MyList.add(file);
                        }
                        th3.start();
                    }
                }
            }
            count++;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);

    }

}
}

标签: javamultithreading

解决方案


@Himanshu 答案的实现。

import java.io.File;

class Lister extends Thread{
    String basepath;

    Lister(String basepath){
        this.basepath = basepath;
    }
     @Override
     public void run(){
         File rootDir = new File(basepath);

         for(File f : rootDir.listFiles()){
             if(f.isDirectory())
                 new Lister(f.toString()).start();
             else
                 System.out.println(f);
         }
     }
}

class Main {
    public static void main(String[] args) {

        new Lister("/").start();
    }
}

此代码有效,但请确保它不会因巨大的目录树而导致内存溢出。为此,您可以添加额外的检查以仅生成您需要的目录。


推荐阅读