Kotlin and Gradle - Reading from stdio

后端 未结 2 1444
旧时难觅i
旧时难觅i 2021-01-12 05:14

I am trying to execute my Kotlin class using the command:

./gradlew -q run < src/main/kotlin/samples/input.txt

Here is my HelloW

2条回答
  •  难免孤独
    2021-01-12 05:41

    Almost, but this doesn't work :'(

    In Theory

    My understanding: < input.txt sets the standard input for the gradlew process, but by default this is not forwarded to your program.

    You want to add this to your build.gradle.kts:

    run {
        standardInput = System.`in`
    }
    

    Sources:
    https://discuss.gradle.org/t/why-doesnt-system-in-read-block-when-im-using-gradle/3308/2
    https://discuss.gradle.org/t/how-can-i-execute-a-java-application-that-asks-for-user-input/3264


    In Practice

    These build configs look about the same to me, yet Groovy works and Kotlin doesn't. I'm starting to think that the Gradle Kotlin DSL doesn't support the standardInput term yet :/

    Here's my working Groovy version if that's any help:

    apply plugin: 'kotlin'
    apply plugin: 'application'
    
    buildscript {
        ext.kotlin_version = '1.1.4'
    
        repositories {
            jcenter()
        }
    
        dependencies {
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        }
    }
    
    repositories {
        jcenter()
    }
    
    dependencies {
        // api => exported to consumers (found on their compile classpath)
        // implementation => used internally (not exposed to consumers)
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }
    
    mainClassName = "samples.HelloWorldKt"
    
    run {
        standardInput = System.in
    }
    

提交回复
热议问题