sivakfil

RxJava - streaming directly to file

Apr 8th, 2017
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. import io.reactivex.Observable;
  2.  
  3. import java.io.FileWriter;
  4. import java.io.IOException;
  5. import java.nio.file.Files;
  6. import java.nio.file.Paths;
  7. import java.util.List;
  8. import java.util.stream.Stream;
  9.  
  10. public class Streaming {
  11.    
  12.     public static void main(String[] args) throws IOException {
  13.         // create Java 8 stream in try-with-resource
  14.         try(Stream<String> stream = Files.lines(Paths.get("data.txt"))) {
  15.            
  16.             // convert stream into Observable (no data loaded yet)
  17.             Observable<List<String>> buffer = Observable.fromIterable(stream::iterator)
  18.                     .buffer(2)
  19.                     .filter(s -> true); // do whatever transformations are needed
  20.            
  21.             // pass reactive stream into writing function (still no data loaded)
  22.             writeToCsv(buffer);
  23.         }
  24.     }
  25.  
  26.     private static void writeToCsv(Observable<List<String>> buffer) throws IOException {
  27.         FileWriter fw = new FileWriter("out.csv");
  28.        
  29.         // subscribe to reactive stream -> now do work and write results directly to file!
  30.         buffer.forEach(record -> fw.append("..."));
  31.     }
  32.    
  33. }
Add Comment
Please, Sign In to add comment