Skip to content

Instantly share code, notes, and snippets.

@mcxiaoke
Forked from akarnokd/RecursiveDirList.java
Last active October 1, 2019 12:37
Show Gist options
  • Save mcxiaoke/be0cbb841970e29143e1 to your computer and use it in GitHub Desktop.
Save mcxiaoke/be0cbb841970e29143e1 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.util.*;
import java.util.concurrent.*;
import rx.*;
import rx.Observable;
import rx.schedulers.Schedulers;
public class RecursiveDirList {
public static Observable<File[]> getFiles(File parent) {
return Observable.create(s -> {
System.out.println(Thread.currentThread() + ": " + parent);
s.onNext(parent.listFiles());
s.onCompleted();
});
}
public static Observable<File> getAllFiles(File root) {
Observable<File[]> ofs = getFiles(root);
return ofs.flatMap(fs -> {
Observable<File> result = Observable.empty();
List<File> regularFiles = new ArrayList<>();
for (File f : fs) {
if (f.isDirectory()) {
result = result.mergeWith(getAllFiles(f));
} else {
regularFiles.add(f);
}
}
return result.mergeWith(Observable.from(regularFiles));
});
}
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newFixedThreadPool(1);
try {
Scheduler single = Schedulers.from(exec);
CountDownLatch cdl = new CountDownLatch(1);
getAllFiles(new File("."))
.subscribeOn(single)
.observeOn(Schedulers.trampoline())
.subscribe(System.out::println, Throwable::printStackTrace, () -> { System.out.println("---"); cdl.countDown(); });
cdl.await();
} finally {
exec.shutdown();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment