2. Basic Console Input Output - mStylias/JavaTopics GitHub Wiki

Output methods

Standard output method

In Java, we can use

  1. System.out.print(): Prints a string
  2. System.out.println(): Prints a string and then moves the cursor to a new line
  3. System.out.printf(): Prints a formatted string
    to send output to the standard output (screen).

Where

  • System is a class
  • out is a public static field: it accepts output data.

Input methods

The most basic input method is using the InputStreamReader with the BufferedReader class.
One way to instantiate it is using System.in as a parameter like so:

BufferedReader standardInput
        = new BufferedReader(new InputStreamReader(System.in));

And can be used in the following way:

String name = input.readLine();

Java contains various input streams, each for a specific purpose
Some of the input streams are the following:

  • FileInputStream: Obtains input bytes from a file in a file system.
  • ByteArrayInputStream: Contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method
  • ObjectInputStream: Deserializes primitive data and objects previously written using an ObjectOutputStream.

Input/Output using System.Console

A new class was introduced in Java 6 called System.console that offers a new way of handling input/output that can be shortened to:

String name = console.readLine("Enter your name: ");
console.printf("Hello %s ", name);

The methods of the console class are the following:

  • format(String fmt, Object... args): works same as System.out.format()
  • printf(String format, Object... args): works same as System.out.printf()
  • readLine(): works same as BufferedReader.readLine()
  • readLine(String fmt, Object... args): prints a formatted string and reads input
  • readPassword(): reads a password to a char array
  • readPassword(String fmt, Object... args): prints a formatted string and reads a password to a char array

It is worth mentioning that the System.console class might not work if the program is running in a non-interactive environment such as inside an IDE. So we have to check to ensure that the Console is actually available for use:

if (console == null) {
    System.out.println("Console is not supported");
    System.exit(1);
}

For example with the basic intellij setup the console class is null if the program is run from inside the IDE

Sources and more details

https://www.geeksforgeeks.org/java-io-input-output-in-java-with-examples/
https://www.programiz.com/java-programming/basic-input-output
https://www.codejava.net/java-se/file-io/java-console-input-output-examples