64

I am writing a console application with Java and gradle. I am using the application plugin and have the required fields correctly configured in build.gradle.

In my main class I have BufferedReader linked with System.in. Here's the problem: When I run gradle run in project directory, the reader does not wait for my console input. BufferedReader#readLine instead returns null on the very first call. This behavior is not desirable for what am I doing.

What is the solution? Is there a separate console application plugin for gradle or do I need to tweak application plugin somehow to suit my needs?

MartyIX
  • 27,828
  • 29
  • 136
  • 207
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
  • 1
    4 years later! If you are running a Windows OS, I have just found that by running the task from a Cygwin terminal this annoying "> Building ..." stuff does not appear. But I've also found that putting `standardInput = System.in` only works for me if I put it inside a specially defined `task`, not when inside `run`. – mike rodent Oct 25 '16 at 18:52
  • 1
    I'd consider this a defect in Gradle. – Robert Nov 20 '19 at 00:24
  • Related Gradle issues: https://github.com/gradle/gradle/issues/1251 and https://github.com/gradle/gradle/issues/2842 – jcsahnwaldt Reinstate Monica Mar 18 '21 at 13:40

4 Answers4

110

By default, the system.in of your Gradle build is not wired up with the system.in of the run (JavaExec) task. You can do the following:

build.gradle (Groovy syntax):

run {
    standardInput = System.in
}

build.gradle.kts (Kotlin DSL syntax):

tasks.named<JavaExec>("run") {
    standardInput = System.`in`
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133
Rene Groeschke
  • 27,999
  • 10
  • 69
  • 78
35

As stated above, add

run {
   standardInput = System.in
}

And run:

gradle console:run -q --console=plain

where:

  • -q runs task in "quiet" mode (to avoid having > Building > :run)
  • --console=plain drops execution status: <=-> 80% EXECUTING [TIME]

Source: https://docs.gradle.org/current/userguide/gradle_command_line.html

iluu
  • 406
  • 3
  • 13
loeschg
  • 29,961
  • 26
  • 97
  • 150
  • this execution status spoils output when I want to use carriage return (it duplicates on each line). do you know how to disable it without --console=plain because it also disables carriage return processing – Yevhenii Nadtochii Nov 05 '19 at 17:55
4

For build.gradle.kts:

tasks.getByName<JavaExec>("run") {
    standardInput = System.`in`
}
diralik
  • 6,391
  • 3
  • 28
  • 52
-4

Chances are, the problem lies in your java code. All the application plugin does is compile the java code, and run the main class that you specify. Can you post the code in your main class that you specified for the application plugin (mainClassName) ?

CaTalyst.X
  • 1,645
  • 13
  • 16
  • I ran the code from within IntelliJ IDEA as well. (By right-clicking the file and selecting `Run .main`.) It works just fine there. – missingfaktor Nov 01 '12 at 06:52