2016-02-09 18 views
1

我試圖使我的團隊在我們的windows計算機上運行的linux框中使用java命令行工具,但是當程序提示輸入時,bufferedReader.readLine()返回null而沒有提示。爲什麼我在執行bufferedReader.readLine()時返回null?在Windows CMD和PowerShell?

下運行,因爲我渴望linux和我的IntelliJ 控制檯運行的時候,但在CMD的PowerShell沒有運行。

public class CliTest { 

public static void main(String[] args) throws Exception { 

    CliTest gen = new CliTest(); 
    gen.run(); 
} 

public void run(){ 
    System.out.println("Hello World"); 
    BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)); 
    try { 
     System.out.print("enter text: "); 
     String input = inputReader.readLine(); 
     System.out.println("input: " + input); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

是成爲一流的運行/使用gradlew從以下蝙蝠腳本構建:

@rem 
@rem run test 
@rem 
echo off 

set LIB=atlib 
set CP=%LIB%/*;%LIB% 

.\gradlew.bat runCliTest 

搖籃任務:

task runCliTest(type:JavaExec) { 
def argList = [] 
main = "com.example.CliTest" 
args = argList 
println(argList) 
workingDir = rootDir 
classpath = sourceSets.main.runtimeClasspath 
} 

這是我希望看到:

Hello World 
enter text: 1 
input: 1 

這就是我得到的:

Hello World 
enter text: input: null 

回答

2

根據您所描述的行爲,這是很清楚的是,在「cmd」並「PowerShell的」情況下,「標準輸入」流是在結束流的位置。因此,調用readLine()時,會得到一個null

這並不奇怪(對我來說)構建工具通常不會在標準輸入上進行輸入。但它也可能是你運行gradle的方式。根據我在這裏找到

...它看起來像你應該使用System.console()得到Console對象的保持,然後使用這些方法來進行交互與用戶。如果與用戶的直接交互是不可能的,則需要允許console()方法返回null

相關問題