java - 如何使用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);
}
}
}
解决方案
@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();
}
}
此代码有效,但请确保它不会因巨大的目录树而导致内存溢出。为此,您可以添加额外的检查以仅生成您需要的目录。
推荐阅读
- python - 如何使用熊猫为每个分组和计数的记录输出每个分组的单个记录
- sql - 设计数据库和关系图和视图
- php - 使 PHP 脚本可编辑并从 SQL 表中提取数据
- python-3.x - 无法在 Ubuntu 18.04 上安装 pip3 和 easy_install
- java - JSTL foreach 不工作。无法从课堂上获取列表?
- sql-server - 为参数传递的多个参数不起作用
- git - 如何将 AzureDevops 上的访问限制为只能访问一个 git-branch
- php - 如何用复合材料遮盖图像,但仅在颜色为黑色的情况下
- c++ - 使用事务内存时的段错误,尝试实现golang的chan模拟
- tsql - 批处理文件不执行 psftp 命令