Kotlin and Gradle-读stdio [英] Kotlin and Gradle - Reading from stdio

查看:96
本文介绍了Kotlin and Gradle-读stdio的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下命令执行我的Kotlin类:

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

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

这是我的 HelloWorld.kt 课:

package samples

fun main(args: Array<String>) {

    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文件中包含的数据.这是我得到的输出:

The code executes, but the data contained inside the input.txt file is not displayed. Here is the output I get:

Hello, world!
null

我希望能够执行上面的gradlew命令,并将input.txt流重定向到stdio.我可以在C ++中轻松地做到这一点.编译.cpp文件后,即可运行:

I want to be able to execute the gradlew command above and the input.txt stream be redirected to stdio. I can easily do that in C++. Once I compile my .cpp file, I can run:

./my_code < input.txt

它会按预期执行.

如何用Kotlin和Gradle实现相同的目的?

How can I achieve the same thing with Kotlin and Gradle?

更新:基于

Update: Based on this answer, I've tried adding this to build.gradle.kts but it is not a valid syntax:

推荐答案

关于run { standardInput = System.in }的AjahnCharles建议是正确的,但是要将其移植到kotlin-dsl,您需要使用其他语法. 在这种情况下,run是任务名称,您可以配置application插件的现有任务. 要在kotlin-dsl中配置现有任务,请使用以下方法之一:

AjahnCharles suggestion about run { standardInput = System.in } is correct, but to port it to kotlin-dsl you need a different syntax. run in this case is the task name and you configure existing task of application plugin. To configure existing task in kotlin-dsl you should use one of this ways:

val run by tasks.getting(JavaExec::class) {
    standardInput = System.`in`
}

val run: JavaExec by tasks
run.standardInput = System.`in`

即将推出的Gradle 4.3版本应提供用于插件编写者的API ,以读取用户输入

The upcoming version of Gradle 4.3 should provide API for plugin writers to read user input.

在这种情况下,Groovy和Kotlin之所以不同是因为Groovy使用动态类型,但是在Kotlin中,您必须指定任务类型以具有自动补全功能,并且只编译配置脚本.

The reason of difference between of Groovy and Kotlin in this case because Groovy uses dynamic types, but in Kotlin you must specify task type to have autocompletion and just to compile config script

这篇关于Kotlin and Gradle-读stdio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆