java.util.scanner 当应用程序以 gradle 运行 启动时抛出 NoSuchElementException

java.util.scanner throws NoSuchElementException when application is started with gradle run

我创建了一个简单的 java "echo" 应用程序,它接受用户的输入并将其返回给他们以演示问题。使用 IntelliJ 的内部 "run" 命令,以及执行由 gradle build 生成的已编译 java 文件时,我可以 运行 这个应用程序而不会出现问题。但是,如果我尝试使用 gradle run 执行应用程序,我会收到从扫描器抛出的 NoSuchElementException。

我认为 gradle 或应用程序插件特别对系统 IO 做了一些奇怪的事情。

申请

package org.gradle.example.simple;

import java.util.Scanner;

public class HelloWorld {
  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    String response = input.nextLine();
    System.out.println(response);
  }
}

build.gradle

apply plugin: 'java'
version '1.0-SNAPSHOT'

apply plugin: 'java'

jar {
    manifest {
        attributes 'Main-Class': 'org.gradle.example.simple.HelloWorld'
    }
}

apply plugin: 'application'

mainClassName = "org.gradle.example.simple.HelloWorld"

sourceCompatibility = 1.5

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

关于如何使用 gradle run 使此应用程序工作的任何想法?

您必须将默认标准输入连接到 gradle,将其放入 build.gradle:

run {
    standardInput = System.in
}

更新:2021 年 9 月 9 日

正如 nickbdyer 在评论 运行 gradlew run 中所建议的那样 --console plain 选项可以避免所有那些嘈杂和烦人的提示

例子

gradlew --console plain run

如果您还想完全删除所有 gradle 任务日志,请添加 -q 选项

例子

gradlew -q --console plain run

除了已接受的答案:如果您使用的是 Gradle Kotlin DSL 而不是普通的 Groovy DSL,则必须编写以下内容:

tasks {
    run {
        standardInput = System.`in`
    }
}

附加说明:我在 Spring 引导应用程序中遇到了类似的问题。在那里,我不得不修改 bootRun 任务而不是 run 任务。

我正在学习使用 Gradle with Kotlin DSL and what worked for me was answered here before

// build.gradle (Groovy syntax)
run {
    standardInput = System.in
}

// build.gradle.kts (Kotlin syntax)
tasks.named<JavaExec>("run") {
    standardInput = System.`in`
}

@MarkusWeninger 提供的解决方案对我不起作用。