我想使用Console類來從用戶獲取輸入,但是當我呼叫System.console()
時返回空對象。在使用System.console之前,我必須更改任何內容嗎?Java:如何從System.console()獲取輸入
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
我想使用Console類來從用戶獲取輸入,但是當我呼叫System.console()
時返回空對象。在使用System.console之前,我必須更改任何內容嗎?Java:如何從System.console()獲取輸入
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
這將取決於您的環境。例如,如果您通過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!");
}
}
}
System.console()在返回null IDE
因此,如果您確實需要使用System.console(),請閱讀此solution from McDowell。
發現了一些很好的答案就在這裏從控制檯讀取,這裏的另一種方法使用「掃描儀」從控制檯讀取:
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將您的應用程序作爲後臺進程運行,而不是作爲系統控制檯的頂級進程運行。
以下內容取athspk's answer並將其合併爲一個循環,直到用戶輸入「exit」。我也寫了一個followup answer,我已經把這段代碼做了測試。
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();
我寫的Text-IO庫,它可以處理System.console(的問題),從IDE中運行的應用程序時,被空。
它引入了一個抽象層,類似於McDowell提出的抽象層。 如果System.console()返回null,則該庫將切換到基於Swing的控制檯。
此外,文本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 + ".");
在this image你可以看到一個基於Swing的控制檯中運行上面的代碼。
這是android嗎? (我從你的用戶ID猜測) – 2011-01-10 07:10:32
看看McDowell的項目「AbstractingTheJavaConsole」:http://illegalargumentexception.googlecode.com/svn/trunk/code/java/AbstractingTheJavaConsole/ – athspk 2011-01-12 01:24:10
@RyanFernandes他的名字如何與他的問題? – 2013-05-01 04:29:58