Ways to read Data From the Console in Java
In this class, We discuss Ways to read Data From the Console in Java.
The reader should have prior knowledge of input and output streams. Click here.
The below example uses a buffered reader class.
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class test
{
public static void main(String args[])throws IOException
{
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String name = reader.readLine();
System.out.println(name);
}
}
The class input stream reader is used to convert bytes to characters.
The object system.in is given as a parameter to input stream reader class
The input stream reader object is given as a parameter to the buffered reader.
The buffered reader class will assign some buffer space to store the data read from the stream.
Instead of reading data from the console each time, Read the buffer data.
The data is read from the buffer to provide speed access.
We can use the methods present in the buffered reader class.
To read the data line by line, use the readline() method.
Another way to read data is by using the scanner class.
Example:
Import java.util.Scanner;
public class test
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println(“You entered string ” + s);
int a = in.nextInt();
System.out.println(“You entered integer ” + a);
float b = in.nextFloat();
System.out.println(“You entered float ” + b);
}
}
The scanner class had so many methods.
We can read data based on int, float, short, etc.
The above example uses methods to read the next line, next int, and next float.