Advertisement
Guest User

Observerable of file lines

a guest
Mar 28th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. package cvi6.demonstrations;
  2.  
  3. import io.reactivex.Observable;
  4. import io.reactivex.ObservableEmitter;
  5. import io.reactivex.ObservableOnSubscribe;
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.nio.file.Files;
  10. import java.nio.file.Path;
  11. import java.nio.file.Paths;
  12.  
  13. public class RxFileReader implements ObservableOnSubscribe<String> {
  14.    
  15.     protected Path filePath;
  16.    
  17.     public RxFileReader(Path filePath) {
  18.         this.filePath = filePath;
  19.     }
  20.  
  21.     public void subscribe(ObservableEmitter<String> emitter) {
  22.         try {
  23.             // prepare buffered reader for file
  24.             BufferedReader br;
  25.             br = Files.newBufferedReader(filePath);
  26.  
  27.             // read line by line
  28.             String line = "";
  29.             while((line = br.readLine()) != null) {
  30.                 // emit each line
  31.                 emitter.onNext(line);
  32.             }
  33.         } catch (IOException e) {
  34.             // emit error
  35.             emitter.onError(e);
  36.         }
  37.         // if all successful, emit on complete
  38.         emitter.onComplete();
  39.     }
  40.    
  41.     public static void main(String[] args) {
  42.         RxFileReader reader = new RxFileReader(Paths.get("data.txt"));
  43.         Observable.create(reader)
  44.         .takeWhile(line -> !line.contains("=="))
  45.         .forEach(System.out::println);
  46.        
  47.         System.out.println("==========");
  48.        
  49.         // this will open the file again and won't continue in reading
  50.         Observable.create(reader)
  51.         .takeWhile(line -> !line.contains("=="))
  52.         .forEach(System.out::println);
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement