我正在尝试使用 Fork / Join机制(List>> forks )机制来搜索磁盘“D:/”上的所有文件。
这是代码。我从JLS实现了这个机制。
public class FileFound_02 {
public static void main(String[] args) {
String searchword = null;
System.out.println("Andrey3k");
// Get Search word from arguments
if( args.length > 0 ) {
searchword = args[0];
System.out.println("____ args.length " + searchword);
}
// Get Disk Drives
File[] rootDrive = File.listRoots();
for(File sysDrive : rootDrive){
System.out.println("Drive : " + sysDrive);
System.out.println("Drive getAbsolutePath: " + sysDrive.getAbsolutePath());
// Scanning D Disk
if( sysDrive.getAbsolutePath().startsWith("D:") ) {
System.out.println("sysDrive.getAbsolutePath(): " + sysDrive.getAbsolutePath());
if( searchword != null ) {
ForkJoinPool forkJoinPool = new ForkJoinPool() ;
List<File> directories = forkJoinPool.invoke(new ScanningDirectory( new File( sysDrive.getAbsolutePath() ), searchword) );
for (int i = 0; i < directories.size(); i++) {
File file = (File) directories.get(i);
System.out.println(file.getAbsolutePath());
}
}
}
}
}
}
public class ScanningDirectory extends RecursiveTask<List<File>> {
File file;
String searchword = "";
public ScanningDirectory(File file, String searchword) {
this.file = file;
this.searchword = searchword;
}
@Override
protected List<File> compute() {
//
List<RecursiveTask<List<File>>> forks = new LinkedList<>();
List files = new ArrayList();
if (file.isDirectory()) {
for (File childFile : file.listFiles()) {
ScanningDirectory task = new ScanningDirectory(childFile, searchword);
forks.add(task);
task.fork();// запусткаем
}
for (RecursiveTask<List<File>> task : forks) {
files.addAll(task.join()); // ждем выполнения задач и результат
}
}
return files ;
}
}
控制台说:
*Exception in thread "main" java.lang.NullPointerException
at andrey3k.FileFound_02.main(FileFound_02.java:40)
Caused by: java.lang.NullPointerException
at andrey3k.ScanningDirectory.compute(ScanningDirectory.java:34)
at andrey3k.ScanningDirectory.compute(ScanningDirectory.java:1)
... 7 more**
有什么问题?我该如何解决?