178

I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using System.console?

Console co=System.console(); System.out.println(co); try{ String s=co.readLine(); } 
5
  • 1
    is this for android ? (i'm guessing from your user id) Commented Jan 10, 2011 at 7:10
  • Are you using eclipse to start your program? Try to start your program without eclipse using java.exe. Commented Jan 10, 2011 at 7:10
  • 5
    Have a look at McDowell's project "AbstractingTheJavaConsole": illegalargumentexception.googlecode.com/svn/trunk/code/java/… Commented Jan 12, 2011 at 1:24
  • 9
    @RyanFernandes How is his name relevant to his question? Commented May 1, 2013 at 4:29
  • Update: New class IO previewed in Java 24, shown in my Answer below. Commented Nov 3, 2024 at 4:29

10 Answers 10

258

Using Console to read input (usable only outside of an IDE):

System.out.print("Enter something:"); String input = System.console().readLine(); 

Another way (works everywhere):

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter String"); String s = br.readLine(); System.out.print("Enter Integer:"); try { int i = Integer.parseInt(br.readLine()); } catch(NumberFormatException nfe) { System.err.println("Invalid Format!"); } } } 

System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.

Sign up to request clarification or add additional context in comments.

5 Comments

why we need BufferedReader to read the input why cant we directly read from InputStreamReader
Got the answer: With a BufferedInputStream, the method delegates to an overloaded read() method that reads 8192 amount of bytes and buffers them until they are needed. It still returns only the single byte (but keeps the others in reserve). This way the BufferedInputStream makes less native calls to the OS to read from the file. Thanks
In case we want to read password from user, stackoverflow.com/questions/22545603/… masks the line with asterisk.
@Learner another reason might be that BufferedReader provides the method readLine() which does not exist for InputStreamReader.
System.console works for me in an IDE, IntelliJ to be specific. Example: System.console ().println ( "Hello world!" );
124
Scanner in = new Scanner(System.in); int i = in.nextInt(); String s = in.next(); 

5 Comments

However nextLine() is very messy to work with. At best it will give you a headache when trying to get whole lines from the console.
@Yokhen could you please given an example where in.nextLine() would create problems?
(1) By default the delimiter of Scanner is space, so when user enters multiple texts, it will cause the software to proceed to next few next() and the logic in our software will be wrong. (2) If I use nextLine() to read the whole full sentence which including space and \n\r, I need to trim() user input. (3) next() will wait for user input but nextLine() will not. (4) I tested useDelimiter("\\r\\n"), but it causes the next() logic in our software somewhere else to be wrong again. Conclusion, it is indeed quite messy to use Scanner to read user input. BufferedReader is the best.
I also have problems with scanner, notably I get a java.util.NoSuchElementException that I don't quite understand.
All this should be inside a try-with-resources and the method should be in.nextLine() if you want to read a line.
36

There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.

public class ConsoleReadingDemo { public static void main(String[] args) { // ==== BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter user name : "); String username = null; try { username = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("You entered : " + username); // ===== In Java 5, Java.util,Scanner is used for this purpose. Scanner in = new Scanner(System.in); System.out.print("Please enter user name : "); username = in.nextLine(); System.out.println("You entered : " + username); // ====== Java 6 Console console = System.console(); username = console.readLine("Please enter user name : "); System.out.println("You entered : " + username); } } 

The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.

Comments

18

It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.

From the command line, it should be fine though. Sample:

import java.io.Console; public class Test { public static void main(String[] args) throws Exception { Console console = System.console(); if (console == null) { System.out.println("Unable to fetch console"); return; } String line = console.readLine(); console.printf("I saw this line: %s", line); } } 

Run this just with java:

> javac Test.java > java Test Foo <---- entered by the user I saw this line: Foo <---- program output 

Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).

Comments

7

Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:

import java.util.Scanner; String data; Scanner scanInput = new Scanner(System.in); data= scanInput.nextLine(); scanInput.close(); System.out.println(data); 

2 Comments

You may not want to call close() the scanner in this case, because it will close System.in and prevent your application from reading from it later on. (Reading later throws error "no line found")
Yes, I agree to that, close() should not be use if the intention is to use System.in later in the program.
5

Try this. hope this will help.

 String cls0; String cls1; Scanner in = new Scanner(System.in); System.out.println("Enter a string"); cls0 = in.nextLine(); System.out.println("Enter a string"); cls1 = in.nextLine(); 

Comments

3

The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LoopingConsoleInputExample { public static final String EXIT_COMMAND = "exit"; public static void main(final String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit"); while (true) { System.out.print("> "); String input = br.readLine(); System.out.println(input); if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) { System.out.println("Exiting."); return; } System.out.println("...response goes here..."); } } } 

Example output:

Enter some text, or 'exit' to quit > one one ...response goes here... > two two ...response goes here... > three three ...response goes here... > exit exit Exiting. 

Comments

3

I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.

It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.

In addition, Text-IO has a series of useful features:

  • supports reading values with various data types.
  • allows masking the input when reading sensitive data.
  • allows selecting a value from a list.
  • allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).

Usage example:

TextIO textIO = TextIoFactory.getTextIO(); String user = textIO.newStringInputReader() .withDefaultValue("admin") .read("Username"); String password = textIO.newStringInputReader() .withMinLength(6) .withInputMasking(true) .read("Password"); int age = textIO.newIntInputReader() .withMinVal(13) .read("Age"); Month month = textIO.newEnumInputReader(Month.class) .read("What month were you born in?"); textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " + "was born in " + month + " and has the password " + password + "."); 

In this image you can see the above code running in a Swing-based console.

Comments

0

Use System.in

http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html

Comments

0

tl;dr

Use new java.io.IO class in Java 25 and later.

String input = IO.readln ( "Enter text: " ); 

System.console does work

Calling System.console() from the IntelliJ IDE does work for me.

On IntelliJ IDEA 2024.3 Beta, with Java 23.0.1, on a MacBook Pro with M1 Pro Apple Silicon running macOS Sonoma 14.7.1, I run this code:

package work.basil.example.console; public class TryIO { public static void main ( String[] args ) { System.console ( ).printf ( "Hello world!" + System.lineSeparator ( ) ); System.console ( ).printf ( "Enter text: " ); String input = System.console ( ).readLine ( ); System.console ( ).printf ( "You typed: " + input + System.lineSeparator ( ) ); } } 

… and get:

Hello world!

Enter text: Bonjour

You typed: Bonjour

print, println, & readln methods on Console

In Java 25 is a new feature that adds methods to the Console class.

  • print
  • println
  • readln

So we can rewrite the code above while avoiding printf, omitting the explicit line-terminator, and passing a user-prompt.

System.console ( ).println ( "Hello world!" ); String input = System.console ( ).readln ( "Enter text: " ); System.console ( ).println ( "You typed: " + input ); 

When run:

Hello world!

Enter text: Bonjour

You typed: Bonjour

For more info, see another Question: Newer easier ways to interact with the console in Java 23+?.

java.io.IO

As part of that new feature in Java 25+, we get a java.io.IO class with static methods for convenient access to those new Console methods.

This IO class implicitly accesses the Console object returned by System.console(). This IO class provides the same method signatures as are being added to Console:

  • print
  • println
  • readln

So we can more briefly write the code above.

IO.println ( "Hello world!" ); String input = IO.readln ( "Enter text: " ); IO.println ( "You typed: " + input ); 

Same output as seen above.

You could of course use static import to drop the IO. prefix. But that is not my style.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.