简体   繁体   中英

Why do I get a null returned when doing a bufferedReader.readLine(); in windows cmd and powershell?

I'm trying to make a java command line tool my team uses on our linux boxes run on our windows machines as well, however when the program prompts for input the bufferedReader.readLine() returns a null without a prompt.

The following runs as I would expect in linux and when running in my IntelliJ console , but not running in cmd or 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();
    }
}

The class in being run/built using gradlew from the following bat script:

@rem
@rem run test
@rem
echo off

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

.\gradlew.bat runCliTest

Gradle task:

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

This is what I would Expect to see:

Hello World
enter text: 1
input: 1

This is what I get:

Hello World
enter text: input: null

Based on the behavior that you have described, it is pretty clear that in the "cmd" and "powershell" cases, the "standard input" stream is at the end-of-stream position. Therefore, when readLine() is called, you get a null .

This is not surprising (to me) build tools don't normally take input on standard input. But it could also be something about the way you are running gradle.

Based on what I found here:

... it looks like you should be using System.console() to get hold of the Console object, and then using its methods to interact with the user. You need to allow for the console() method returning null if direct interaction with the user is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM