javaproject-reactorfluxspring-reactor

How to read file lines while they appear and represent them as Flux?


Assume we depend on Reactor 3 (i.e in a Spring 5 application) and a text file my/file.txt.

I need to subscribe to the text file lines (both existing ones and those that will appear in the future) and create a Flux<String>. If you wish, neglect blocking IO reads concerns, let's just reveal the principle of building such subscription.

For simplicity assume that we print those lines to std output:

flowLinesFrom(Path.of("my/file.txt"))
   .subscribe(System.out::println);     

What is the proper way to implement Flux<String> flowLinesFrom(Path)?


Solution

  • You can use this like so

    //Create FluxTailer
    FluxTailer tailer = new FluxTailer(
        //The file to tail
        Path.of("my/file.txt").toFile(),
        //Polling interval for changes
        Duration.ofSeconds(1)
    );
    
    //Start tailing
    tailer.start();
    
    //Subscribe to the tailer flux
    tailer.flux().subscribe(System.out::println);
    
    //Just for demo you wait for 10 seconds
    try{
        Thread.sleep(10000);
    }catch (Exception e){}
    
    //Stop the tailer when done, will also complete the flux
    tailer.stop();
    

    You can start stop as you please and also set to read from start or end of file using

    tailer.readFromStart();
    tailer.readFromEnd();