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 }
- 从cmd运行时,Spring AOP不工作
- Gradle:运行某个类的任务
- Android Studio 2.2无法找到所有kotlin文件的引用
- Kotlin,Java,multidex,Dagger 2,Butterknife和Realm:transformClassesWithMargingForDebug:重复条目:org / jetbrains / annotations / NotNull.class
- Gradle 3.0.0(在Android Studio 3.0中)重新排列任务序列(用Kotlin模块编译时)?
- Kotlin Dagger2找不到符号ApplicationModule_ProvideApplicationFactory
- Kotlin kapt无法看到支持注释
- 在buildscript中的分机不能被Gradle Kotlin DSL识别
- 在库模块中使用Kotlin,而不在app模块中使用它