Java: How to get input from System.console()
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
Are you using eclipse to start your program? Try to start your program without eclipse using java.exe.
9 Answers 9
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.
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 .
Scanner in = new Scanner(System.in); int i = in.nextInt(); String s = in.next();
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.
(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.
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.
Reading User Input from Console in Java
In this Java tutorial, we will learn how to read the user input text from the console in Java. Reading console input in programs may be necessary to make applications interactive.
Console class is from java.io package and is used to read from and write to the character-based console.
The System.console() is used to get the reference of the system console. Note that if JVM has been launched with a background job then the program will not have a console. In this case, invocation of System.console() method will return null .
- The readLine() reads a single line of text from the console.
- The readLine(line) writes the line into the console and then reads the user input from the console.
- The readPassword() is used to read the secure input. For example, passwords and encryption keys.
- The readPassword(line) prompts the line into the console and reads the secure user input. For example, passwords and encryption keys.
- Passing a null argument to any method in this class will cause a NullPointerException to be thrown.
Console console = System.console(); String inputString = console.readLine("Enter Your Name: "); System.out.println("The name entered: " + inputString);
Enter Your Name: Lokesh The name entered: Lokesh
BufferedReader is supported since Java 1.1. We may see its usage in legacy Java applications. To read console input, we shall wrap the System.in (standard input stream) in an InputStreamReader which again wrapped in a BufferedReader class.
BufferedReader reads text from the console, buffering characters so as to provide for the efficient reading of user input. It makes the read operations from InputStreamReader – less costly.
System.out.print("Enter Your Name: "); //Prompt BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String inputString = bufferRead.readLine(); System.out.println("The name entered: " + inputString);
Enter Your Name: Lokesh The name entered: Lokesh
In Java, System.in represents the standard input. By default, it is the system console.
The Scanner class, when reading from the console, provides methods to read different types of data e.g. integers, numbers, strings, etc.
Scanner scanner = new Scanner(System.in); System.out.println("Enter name, age and salary:"); String name = scanner.nextLine(); int age = scanner.nextInt(); double salary = scanner.nextDouble(); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary);
Above all techniques are equally effective, but I personally like the java.io.Console way. It simply makes code more readable. What is your choice to read the test from Console in Java.
What’s the best way to get console-input in Java?
Getting output with Java is pretty easy as you can make use of System.out.print and the like. Input, on the other hand, seems a little different. Some people recommend java.util.Scanner while others recommend java.io.BufferedReader, and I’m sure there’s plenty of other recommendations. The two methods above are most regularly-used. Neither seem to present very nice options (in my opinion). So, is there any better way to get input from a console window in Java? And if there isn’t, which should I choose?
7 Answers 7
I feel Scanner is helpful in two aspects,
1) you can get input from command prompt and infuture if you want to change to file system, it will be quick 2) While reading integer inputs you don't need to parse
I think, The scanner class is quite helpful. For example with BufferedReader, you have to read a line at a time and parse it for the values. But in the scanner you get integers with nextInt() method etc.
Scanner is handy, but it is slower than BufferedReader.
- For console input you can use System.console() , which is available in/after JAVA 1.6 it has options for readPassword() (will not show entered character on console as well do not cache it) and readLine() .
String name = System.console().readLine(); //using java.io.*
Scanner in = new Scanner(System.in); // using java.util.Scanner; String s = in.nextLine(); // for reading string int a = in.nextInt(); // for reading int float b = in.nextFloat(); // for reading float
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // using java.io.* String name = reader.readLine(); // it reads everything into string
p.s: The System.console() method does not work in non-interactive environments (i.e. an IDE).
Trying to read from the console in Java
I have just started learning Java with IntelliJ IDE. I know a bit C# so the logic makes some sense, however there is one thing so far I couldn’t get over it. How do I read from the console? In C#, you could easily read what the human typed into it, using Console.ReadLine() . In Java, System.console().readLine(); does not work for me and throws a NullPointerException . What am I missing here?
First result for googling last words from title of your question: «read from console JAVA» gives: Java: How to get input from System.console(). Also System.console().readLine(); works fine for me (if I run my code via console, outside of IDE). We need to see your code and know how are you using it and what exception you are getting.
6 Answers 6
NOTE: problem doesn’t appear when we run your code from console/terminal via java [options] [MainClass] so if this is valid solution for you you can stop reading here. Rest of this answer is for people who are using some IDEs to run their code.
Problem
Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).
Difference between these two programs is that javaw runs Java code without association with current terminal/console (which is useful for GUI applications), and since there is no associated console window System.console() returns null . Because of that System.console().readLine() ends up as null.readLine() which throws NullPointerException since null doesn’t have readLine() method (nor any method/field).
But just because there is no associated console, it doesn’t mean that we can’t communicate with javaw process. This process still supports standard input/output/error streams, so IDEs process (and via it also we) can use them via System.in , System.out and System.err .
This way IDEs can have some tab/window and let it simulate console.
For instance when we run code like in Eclipse:
package com.stackoverflow; public class Demo < public static void main(String[] args) throws Exception < System.out.println("hello world"); System.out.println(System.console()); >>
which shows that despite javaw.exe not having associated console ( null at the end) IDE was able to handle data from standard output of the javaw process System.out.println(«hello world»); and show hello world .
General solution
To let user pass information to process use standard input stream ( System.in ). But since in is simple InputStream and Stream s are meant to handle binary data it doesn’t have methods which would let it easily and properly read data as text (especially if encoding can be involved). That is why Readers and Writers ware added to Java.
So to make life easier and let application read data from user as text you can wrap this stream in one of the Reader s like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn’t accept Streams but Reader s, so we need some kind of adapter which will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader exists.
So code which would let application read data from input stream could look like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Hello. Please write your name: "); String name = br.readLine(); System.out.println("Your name is: "+name);
Preferred/simplest solution — Scanner
To avoid this magic involving converting Stream to Reader you can use Scanner class, which is meant to read data as text from Streams and Readers.
This means you can simply use
Scanner scanner = new Scanner(System.in); //. String name = scanner.nextLine();
to read data from user (which will be send by console simulated by IDE using standard input stream).