Java: 如何从 System.sole ()获取输入

我试图使用 Console 类从用户获得输入,但是当我调用 System.console()时返回一个 null 对象。在使用 System.sole 之前,是否需要更改任何内容?

Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
700070 次浏览

这将取决于您的环境。例如,如果您通过 javaw运行 Swing UI,那么就会显示 不是控制台。如果您在 IDE 中运行,那么它将在很大程度上取决于特定 IDE 对控制台 IO 的处理。

但是从命令行来看,应该没有问题。示例:

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

java运行这个程序:

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

另一种选择是使用 System.in,您可能希望将其包装在 BufferedReader中以读取行,或者使用 Scanner(同样包装 System.in)。

Scanner in = new Scanner(System.in);


int i = in.nextInt();
String s = in.next();

使用控制台读取输入(只能在 IDE 之外使用) :

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

另一种方式(在任何地方都适用) :

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!");
}
}
}

Sole ()在 IDE 中返回 null。
因此,如果您真的需要使用 System.console(),请阅读此 麦克道尔的解决方案

在这里找到了一些关于从控制台读取的好答案,这里有另一种方式使用“扫描仪”从控制台读取:

import java.util.Scanner;
String data;


Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();


scanInput.close();
System.out.println(data);

从控制台/键盘读取输入字符串的方法很少。下面的示例代码演示如何使用 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);


}
}

代码的最后一部分使用了 java.io.Console类。在通过 Eclipse 运行演示代码时,无法从 System.console()获得 Console 实例。因为 eclipse 将应用程序作为后台进程运行,而不是作为带有系统控制台的顶级进程运行。

以下代码采用 阿斯匹克的回答,并使其成为一个不断循环的 阿斯匹克的回答,直到用户键入“ exit”。我还编写了一个 跟进答复,在其中我使用了这段代码并使其可测试。

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...");
}
}
}

输出示例:

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.

试试这个,希望能有帮助。

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

我编写了 文本输入库,它可以处理从 IDE 中运行应用程序时 System.sole ()为 null 的问题。

它引入了一个类似于 ABc0提出的抽象层。 如果 System.sole ()返回 null,则库切换到基于 Swing 的控制台。

此外,Text-IO 还有一系列有用的功能:

  • 支持读取各种数据类型的值。
  • 允许在读取敏感数据时屏蔽输入。
  • 允许从列表中选择值。
  • 允许指定输入值的约束(格式模式、值范围、长度约束等)。

用法例子:

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 + ".");

这个画面中,您可以看到上面的代码在基于 Swing 的控制台中运行。