尝试从 Java 中的控制台读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26470972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to read from the console in Java
提问by LidorA
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.
我刚刚开始使用 IntelliJ IDE 学习 Java。我知道一点 C#,所以逻辑是有道理的,但是到目前为止,我无法克服一件事。
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
.
我如何从控制台读取?在 C# 中,您可以使用Console.ReadLine()
. 在 Java 中, System.console().readLine();
对我不起作用并抛出一个NullPointerException
.
What am I missing here?
我在这里缺少什么?
回答by Nagakishore Sidde
java.util.Scanner
API is what you are looking for.
java.util.Scanner
API 就是您正在寻找的。
回答by Pshemo
Problem
问题
Most IDEs are using javaw.exe
instead of java.exe
to run Java code (see image below).
大多数 IDE 使用javaw.exe
而不是java.exe
运行 Java 代码(见下图)。
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).
这两个程序之间的区别在于javaw
运行 Java 代码而不与当前终端/控制台关联(这对 GUI 应用程序很有用),并且由于没有关联的控制台窗口System.console()
返回null
. 因为这System.console().readLine()
最终成为null.readLine()
which throwsNullPointerException
因为null
没有readLine()
方法(也没有任何方法/字段)。
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
.
但是仅仅因为没有关联的控制台,并不意味着我们不能与javaw
进程通信。此过程仍然支持标准输入/输出/错误流,因此 IDE 过程(以及通过它我们)可以通过System.in
,System.out
和使用它们System.err
。
This way IDEs can have some tab/window and let it simulateconsole.
这样 IDE 可以有一些选项卡/窗口并让它模拟控制台。
For instance when we run code like in Eclipse:
例如,当我们像在 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());
}
}
we will see as result
我们会看到结果
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
.
这表明尽管javaw.exe
没有关联的控制台(null
最后)IDE 能够处理来自javaw
进程标准输出的数据System.out.println("hello world");
并显示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 binarydata 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.
要让用户将信息传递给进程,请使用标准输入流 ( System.in
)。但是由于它in
很简单InputStream
并且Stream
s 旨在处理二进制数据,因此它没有方法可以让它轻松正确地将数据读取为文本(尤其是在可能涉及编码的情况下)。这就是为什么Readers
和Writers
ware 添加到 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 adapterwhich will simulate Reader and be able to translate bytes to text. But that is why InputStreamReader
exists.
因此,为了让生活更轻松并让应用程序从用户读取数据作为文本,您可以将此流包装在其中之一中,Reader
这样BufferedReader
您就可以使用readLine()
方法读取整行。不幸的是,这个类不接受Streams
但Reader
s,所以我们需要某种适配器来模拟 Reader 并能够将字节转换为文本。但这就是InputStreamReader
存在的原因。
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 magicinvolving converting Stream to Reader you can use Scanner
class, which is meant to read data as text from Streams and Readers.
为了避免这种将 Stream 转换为 Reader 的魔法,您可以使用Scanner
class,它旨在从 Streams 和 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).
从用户读取数据(将由 IDE 使用标准输入流模拟的控制台发送)。
回答by Muhammed Ozdogan
If you realy need to Console object you can compile your class from command line. Firstly in my java file first statement is package com.inputOutput;
如果你真的需要 Console 对象,你可以从命令行编译你的类。首先在我的java文件中,第一条语句是package com.inputOutput;
Go in your project "src
" folder and compile it like : "javac com/inputOutput/Password.java
" 'com
' and 'inputOutput
' are folder(package). Run your class file in src
folderjava com.inputOutput.Password
". It had worked work for me.
进入你的项目“ src
”文件夹并像这样编译它:“ javac com/inputOutput/Password.java
”' com
'和' inputOutput
'是文件夹(包)。在src
文件夹java com.inputOutput.Password
“中运行您的类文件。它对我有用。
回答by u6856342
You could use an Jframe.
您可以使用 Jframe。
JFrame frame = new JFrame("titile");
// prompt the user to enter their code
String code = JOptionPane.showInputDialog(frame, "promt here");