Skip to content

Instantly share code, notes, and snippets.

@jreber
Last active December 31, 2015 14:08
Show Gist options
  • Save jreber/7998019 to your computer and use it in GitHub Desktop.
Save jreber/7998019 to your computer and use it in GitHub Desktop.
First version of FileWatcher
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import rx.Observable;
import rx.Observable.OnSubscribeFunc;
import rx.Observer;
import rx.Subscription;
import rx.util.functions.Action1;
public class FileWatcher implements OnSubscribeFunc<String> {
public static void main(String... args) {
if (args.length == 0) {
System.out.println("No files specified.");
return;
}
for (final String file : args) {
System.out.println(">> Adding watcher for file \"" + file + "\"...");
try {
Observable<String> newObservable = Observable.create(create(file));
newObservable.subscribe(new Action1<String>() {
@Override
public void call(String t1) {
System.out.printf("%20s\t%s\n", file, t1);
}
});
} catch (FileNotFoundException e) {
System.out.println(">> ERROR: File \"" + file + "\" was not found.");
}
}
}
private final Path path;
public static FileWatcher create(String sPath) throws FileNotFoundException {
Path path = Paths.get(sPath);
if (!Files.isReadable(path))
throw new FileNotFoundException(sPath);
return new FileWatcher(path);
}
private FileWatcher(Path path) {
this.path = path;
}
@Override
public Subscription onSubscribe(Observer<? super String> observer) {
try (BufferedReader reader = new BufferedReader(new FileReader(path.toFile()))) {
String newLine = "";
while ((newLine = reader.readLine()) != null)
observer.onNext(newLine);
} catch (FileNotFoundException e) {
observer.onNext(">> ERROR: File could not be found.\n" + e);
observer.onError(e);
} catch (IOException e) {
observer.onNext(">> ERROR: File could not be read.\n" + e);
observer.onError(e);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment