I have summarized a method to directly obtain input using System.in.read()
without using java.util.Scanner
in Java.
Environment
- Java 11
[Review] How to Get Standard Input Using Scanner
To obtain standard input using Scanner
, you do the following. Create an instance by passing System.in
to the constructor of Scanner
.
1 2 3 4 5 6 7 8 |
import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println(sc.next()); } } |
The Scanner
instance is convenient, not only with next
but also with methods that return values as numbers, such as nextInt
, nextDouble
, and methods that return values as booleans, such as nextBoolean
.
How to Get Standard Input Directly from System.in
To obtain standard input directly from System.in
, use System.in.read()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.IOException; public class StandardInput { public static String read() throws IOException { StringBuilder s = new StringBuilder(); while (true) { char c = (char) System.in.read(); if (c == '\n') break; s.append(c); } return s.toString(); } } |
StandardInput.read()
allows you to obtain the string of standard input. It does not return a value until Enter is pressed in standard input. System.in
returns each character one by one until Enter is pressed ('\n'
is entered).