Mike Flynn
Mike Flynn

Reputation: 1027

How do streams work when code is executed step by step?

For example, in java, to read input from the console you would write something like this:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

So in the line String s = bufferRead.readLine(), the code just waits for the input to come in and then goes to the next step, but what if you want to look at a continuous stream of strings trying to parse out pieces of it, for example, reading a stream of Twitter statuses and only saving the ones that have the word "Obama" in it or something?

I don't understand how the code could be executing line-by-line, while handling input from the stream, and then suddenly detecting when input is given and saving it.

Upvotes: 0

Views: 471

Answers (3)

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

bufferRead.readLine(); doesn't return back to the calling code, until the user presses the return key.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533500

The console is line buffered. This means an entire line comes as once to the Java process so it doesn't see you writing characters or hitting back space to delete them etc.

I suspect you don't need to see how it does this. Perhaps you could describe what problem you are trying to solve?

Upvotes: 0

Alex Coleman
Alex Coleman

Reputation: 7326

That code write there is only set to read in one line of input, from the system's input (that is, the console). It's setup so that when you do readLine, it will read a line from the input. You have to type in something ("Hello there") and hit enter, and it will take that, and put it in String s. If you want to parse stuff out, do it manually afterwords

if(s.contains("Obama")) {
    //blah
}

Upvotes: 0

Related Questions