Kotlin和Gradle – 从stdio读取
我正在尝试使用以下命令来执行我的Kotlin类:
./gradlew -q run < src/main/kotlin/samples/input.txt
这是我的HelloWorld.kt类:
package samples fun main(args: Array) { println("Hello, world!") val lineRead = readLine() println(lineRead) }
这是我的build.gradle.kts :
plugins { kotlin("jvm") application } application { mainClassName = "samples.HelloWorldKt" } dependencies { compile(kotlin("stdlib")) } repositories { jcenter() }
代码执行,但input.txt文件内包含的数据不显示。 这是我得到的输出:
Hello, world! null
我希望能够执行上面的gradlew命令,并将input.txt流重定向到stdio。 我可以很容易地在C ++中做到这一点。 一旦我编译我的.cpp文件,我可以运行:
./my_code < input.txt
并按预期执行。
我怎样才能用Kotlin和Gradle实现同样的事情?
更新 :基于这个答案 ,我已经尝试将此添加到build.gradle.kts,但它不是一个有效的语法:
AjahnCharles有关run { standardInput = System.in }
是正确的,但要将其移植到kotlin-dsl,则需要使用不同的语法。 在这种情况下run
是任务名称,并配置application
插件的现有任务。 要在kotlin-dsl中配置现有任务,您应该使用以下方法之一:
val run by tasks.getting(JavaExec::class) { standardInput = System.`in` }
要么
val run: JavaExec by tasks run.standardInput = System.`in`
即将到来的Gradle 4.3版本应该为插件编写者提供读取用户输入的API 。
在这种情况下,Groovy和Kotlin之间的区别是因为Groovy使用动态types,但是在Kotlin中,您必须指定任务types来自动完成,只需要编译配置脚本
差不多,但这不起作用:’(
理论上
我的理解: < input.txt
设置gradlew进程的标准输入,但默认情况下,这不会被转发到您的程序。
你想添加到你的build.gradle.kts:
run { standardInput = System.`in` }
资料来源:
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
在实践中
这些构建配置对我来说看起来差不多 ,但Groovy工作,Kotlin没有 。 我开始认为Gradle Kotlin DSL不支持standardInput
术语:/
这是我的工作Groovy版本,如果有任何帮助:
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 }
- Gradle在Kotlin和JUnit 5中找不到我的测试
- 无法安装android studio 3.0的gradle
- 如何在两个build.gradle.kts文件之间共享构建配置?
- Gradle同步失败:无法GET'https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin/1.1.3-2/kotlin-gradle-plugin-1.1.3-2.pom'
- 我怎样才能把一个groovy任务gradle转换成Gradle Kotlin DSL来生成一个pom.xml?
- 在Android 4.4上添加Kotlin配置后,DexFile不包含生成的类
- 编译Groovy和Kotlin?
- Kotlin插件错误:无法为类org.jetbrains.kotlin.gradle.tasks.KotlinCompile生成代理类
- 什么是Kotlin Gradle依赖关系中的“实现”?