Read Text from console in Java

How to read text from the console is very important to Java developers know. It’s a very basic coding of core java. There are many ways to read text from the console, we are sharing some ways to do it.

Read Text from console in Java

A way to Read Text from console

Here is 2 ways with example to read text from console, you can do with different also.

1.  Using BufferReader

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

public class ReadText {
	public static void main(String arg[]){
		BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter Text : ");
		try {
			String enterStr=bufferedReader.readLine();
			System.out.println("Your Text : " + enterStr);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2.  Using Scanner

In Java 5, java.util.Scanner is used for this purpose.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

import java.util.Scanner;

public class Hello {

    public static void main(String ar[]){
        System.out.print("Enter your username: ");
        Scanner in = new Scanner(System.in);
        String input = in.nextLine();
        System.out.println("Your name is : " + input);
    }
}

Fore Reading a text from file follow this tutorial – Java Read File Text

Do comment if you have any other example or doubt or suggestion.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Read Text from console are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.