1

NOTE: I have just marked this question as a duplicate.

Here is the answer: Console application with Java and gradle


I created a Gradle application that simply receives some input as a String?. When I try using the "run" task, stringInput evaluates to null automatically. I have already tested this with the Kotlin compiler in the terminal, and it works as expected.

Here is the main code below:

package com.s12works.readLineTest

fun main() {
    print("Enter text: ")
    val stringInput: String? = readLine()
    println("You entered: $stringInput")
}

The output from running this application with the run task:

**> Task :app:run**
Enter text:
You entered: null

How can I stop this? Any help would be appreciated.

user18798042
  • 107
  • 7
  • 1
    From the docs [here](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/read-line.html) `Return the line read or null if the input stream is redirected to a file and the end of file has been reached.` – Nongthonbam Tonthoi Oct 24 '22 at 05:05
  • 1
    Other reasons why readLine() might hit end-of-file include the user entering the end-of-file indicator (e.g. Ctrl+D on Unix/macOS), or the program running on a platform such as an online IDE which doesn't support user input. – gidds Oct 24 '22 at 18:13
  • I found something promising here: https://stackoverflow.com/questions/65000410/kotlin-readline-function-not-working-properly. I am just confused when the answer says "change JRE options through `Edit Configurations`." Is this something specific to Intellij IDEA? – user18798042 Oct 25 '22 at 02:01
  • I used `java.util.Scanner` as well. It also does not work. – user18798042 Oct 25 '22 at 02:16

1 Answers1

1

The run task of the application plugin is of type JavaExec. As you can see in the DSL reference for the JavaExec (https://docs.gradle.org/current/dsl/org.gradle.api.tasks.JavaExec.html#org.gradle.api.tasks.JavaExec:standardInput) the default input stream is set to empty. To change this behavior you can add the following to your build script:

run {
 standardInput = System.in
}
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219