【问题标题】:Why do I get a null returned when doing a bufferedReader.readLine(); in windows cmd and powershell?为什么在执行 bufferedReader.readLine() 时返回 null;在 Windows cmd 和 powershell 中?
【发布时间】:2016-05-20 02:55:26
【问题描述】:

我正在尝试使我的团队在我们的linux 框上使用的 java 命令行工具也可以在我们的 Windows 机器上运行,但是当程序提示输入时,bufferedReader.readLine() 会在没有提示的情况下返回 null。

linux 和在我的IntelliJ 控制台 中运行时,以下运行如我所料,但在cmdpowershell 中没有运行.

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

使用以下 bat 脚本中的 gradlew 运行/构建的类:

@rem
@rem run test
@rem
echo off

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

.\gradlew.bat runCliTest

Gradle 任务:

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

【问题讨论】:

    标签: java powershell intellij-idea cmd


    【解决方案1】:

    根据您描述的行为,很明显在“cmd”和“powershell”情况下,“标准输入”流位于流的末尾位置。因此,当readLine() 被调用时,你会得到一个null

    这并不奇怪(对我来说)构建工具通常不接受标准输入的输入。但这也可能与您运行 gradle 的方式有关。

    根据我在这里找到的:

    ...看起来您应该使用System.console() 来获取Console 对象,然后使用其方法与用户进行交互。如果无法与用户直接交互,则需要允许 console() 方法返回 null

    【讨论】:

      猜你喜欢
      • 2013-06-29
      • 1970-01-01
      • 2011-03-29
      • 2014-06-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多