Search code examples
gradleinputstreamblockingsystem.in

Can't get Gradle to use System.in


This question explains how to use System.in when running a task to run a specific class in a project.

But for me currently it's not working: although I have included the application plugin and the following lines in build.gradle:

mainClassName = "misc.StreamsExp"
run{ 
    standardInput = System.in 
}
task stream( type: JavaExec, dependsOn: assemble ){
    classpath sourceSets.main.runtimeClasspath
    main = "misc.StreamsExp"
}

the line with readLine in the app code below should be blocking but it's not:

BufferedReader br = new BufferedReader(new InputStreamReader( System.in ));

String enteredLine = "";
while( enteredLine == null || ! enteredLine.equals( "q" )){
    System.out.println( "spuds");
    enteredLine = br.readLine();
}

... instead the thing just spins on forever:

spuds
spuds
spuds
...

NB I am on a Windows 10 OS, with Java 8.91. I have tried both the Windows DOS console and Cygwin.
NB2 The same thing occurs when I run this stream task inside Eclipse (Gradle STS Eclipse plugin)... but not when I do Run as --> Java application: then the blocking occurs as expected.


Solution

  • Hah... one of those sits where you think you're gonna be stumped forever and you find the solution 2 mins after posting to SO! I'll leave it here for anyone else...

    The answer is to put the line standardInput = in the task you're running, like so:

    task stream( type: JavaExec, dependsOn: assemble ){
        standardInput = System.in
        classpath sourceSets.main.runtimeClasspath
        main = "misc.StreamsExp"
    }
    

    Strangely, the prompt "spuds" is followed in the Windows DOS terminal by

    > Building 88% > :stream

    ... which is a known "bug" referred to in the question I referenced. In Cygwin this bug does not happen.

    CAVEAT: this works in the Windows DOS terminal and the Cygwin terminal... it does NOT solve the problem when running the bespoke stream task in Eclipse!