gpt4 book ai didi

java - 为什么在执行 bufferedReader.readLine(); 时返回 null在 Windows cmd 和 powershell 中?

转载 作者:行者123 更新时间:2023-11-30 03:03:50 26 4
gpt4 key购买 nike

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

以下内容按照我的预期在 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();
}
}

使用来自以下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

最佳答案

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

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

根据我在这里找到的内容:

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

关于java - 为什么在执行 bufferedReader.readLine(); 时返回 null在 Windows cmd 和 powershell 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com