如何使用Java多线程扫描多个目录

时间:2018-12-14 06:25:30

标签: java multithreading

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

我已经完成了部分代码,但无法正常工作,您能帮我什么正确的方法吗?

代码

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

    }

}
}

2 个答案:

答案 0 :(得分:0)

如果您有目录(包括子目录),并且想要列出所有文件。 最简单但有效的方法是遍历目录,只有两个选项,即文件或目录。

如果是文件,只需对其命名,不要为其生成新线程。 如果是目录,请产生一个新线程,然后重新使用相同的代码遍历新产生的线程中该目录中的文件或子目录。

如果您可以提供示例输出,那么也许我们可以提供进一步的帮助。但是直到那时,我还没有看到代码中使用同步。

答案 1 :(得分:0)

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

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