non-blocking bufferedreader code example

Example: non-blocking bufferedreader

import java.io.BufferedReader;

public class nonblockingIO {
  
  public void read() {
    
    // Initialising BufferedReader object
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    // This can be replaced for a conditional loop
    while (true) {
      
      /* This is the crucial line.
        This line checks if there is any data in the buffered BufferedReader.
        If there isn't any data, the code inside the if statement is skipped
        and the buffered reader is thus non-blocking as the program does not
        wait for a user input (i.e. the user to press enter) */
      if (br.ready()) {
        
        // Reading data from the buffered reader
        String output = br.readLine();

      }

      // Other code here...

    }
    
  }
  
}

Tags:

Misc Example