Java - IO - Standard Streams

About

Management

Manipulation

For historical reasons, Standard Streams are byte streams and not character streams

  • System.out and System.err are defined as PrintStream objects. PrintStream is technically a byte stream but emulate many of the features of character streams (println,…)

Read a manual input (stream)

System.in is a byte stream with no character stream features. To use Standard Input as a character stream, wrap System.in in InputStreamReader.

InputStreamReader in = new InputStreamReader(System.in);

Example:

public class GreetingMachine {
    public static void main(String[] args) throws Exception {
        String inputFile = null;
        if ( args.length>0 ) inputFile = args[0];
        java.io.InputStream is = System.in;
        if ( inputFile!=null ) {
            is = new FileInputStream(inputFile);
        }

        System.out.println("The greeting machine. Who are we greeting ?:");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String input = br.readLine();              // get first expression

        while ( input!=null ) {
            System.out.println("Greeting ! "+input);
            input = br.readLine();
        }
    }
}
The greeting machine. Who are we greeting ?:
Nico <- Text entered
Greeting ! Nico <- Answer
Rixt <- Text entered
Greeting ! Rixt <- Answer

Reassignment

Read a pipe redirection in the main class

int counter = 0;
int input;			}
while((input=System.in.read())!=-1){
	counter++;
	System.out.println(counter+ " - "+input+" char ("+(char) input+")");
}

Printing on the same line

Whatever ... \r

The \r carriage return move the cursor back to the beginning of the line. Terminal - Escape Sequence (Control sequence) ??

System.out.print() (not System.out.println() that adds a end of line)


Powered by ComboStrap