尝试从 Java 中的控制台读取 [英] Trying to read from the console in Java

查看:22
本文介绍了尝试从 Java 中的控制台读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 IntelliJ IDE 学习 Java.我知道一点 C#,所以逻辑有一定道理,但是到目前为止,我无法克服一件事.

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.

如何从控制台读取数据?在 C# 中,您可以使用 Console.ReadLine() 轻松读取人类输入的内容.在 Java 中,System.console().readLine(); 对我不起作用并抛出 NullPointerException.

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.

我在这里遗漏了什么?

推荐答案

注意:当我们通过 java [options] [MainClass 从 控制台/终端运行您的代码时,问题不会出现] 所以如果这对你来说是有效的解决方案,你可以停止阅读这里.此答案的其余部分适用于使用某些 IDE 来运行其代码的人.

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.

大多数 IDE 使用 javaw.exe 而不是 java.exe 来运行 Java 代码(见下图).

Most IDEs are using javaw.exe instead of java.exe to run Java code (see image below).

这两个程序的区别在于javaw运行Java代码与当前终端/控制台没有关联(这对GUI应用程序很有用),并且由于没有关联控制台窗口 System.console() 返回 null.由于 System.console().readLine() 最终为 null.readLine() 抛出 NullPointerException 因为 null 没有 readLine() 方法(也没有任何方法/字段).

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进程通信.这个进程仍然支持标准的输入/输出/错误流,所以 IDE 进程(以及通过它我们)可以通过 System.inSystem.out 使用它们>System.err.

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.

这样 IDE 可以有一些选项卡/窗口,并让它模拟控制台.

This way IDEs can have some tab/window and let it simulate console.

例如,当我们像在 Eclipse 中一样运行代码时:

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());
    }

}

我们会看到结果

这表明尽管 javaw.exe 没有关联的控制台(最后是 null)IDE 能够处理来自 javaw<的标准输出的数据/code> 处理 System.out.println("hello world"); 并显示 hello world.

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.

让用户将信息传递给进程使用标准输入流(System.in).但是由于 in 是简单的 InputStreamStreams 是为了处理 binary 数据它没有方法将让它轻松且正确地将数据作为文本读取(尤其是在可能涉及编码的情况下).这就是为什么将 ReadersWriters 添加到 Java 中的原因.

To let user pass information to process use standard input stream (System.in). But since in is simple InputStream and Streams 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.

因此,为了让生活更轻松并让应用程序从用户读取数据作为文本,您可以将此流包装在 Reader 之一中,例如 BufferedReader 这将让您阅读整个与 readLine() 方法一致.不幸的是,这个类不接受 Streams 而是 Readers,所以我们需要某种适配器来模拟 Reader 并能够转换字节到文本.但这就是 InputStreamReader 存在的原因.

So to make life easier and let application read data from user as text you can wrap this stream in one of the Readers like BufferedReader which will let you read entire line with readLine() method. Unfortunately this class doesn't accept Streams but Readers, 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);

首选/最简单的解决方案 - 扫描仪

为了避免这种涉及将 Stream 转换为 Reader 的魔法,您可以使用 Scanner 类,该类旨在从 Streams 和 Readers 中以文本形式读取数据.

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();

从用户读取数据(将由IDE模拟的控制台使用标准输入流发送).

to read data from user (which will be send by console simulated by IDE using standard input stream).

这篇关于尝试从 Java 中的控制台读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆