【问题标题】:java.util.scanner throws NoSuchElementException when application is started with gradle runjava.util.scanner 在使用 gradle run 启动应用程序时抛出 NoSuchElementException
【发布时间】:2016-04-19 15:51:49
【问题描述】:

我创建了一个简单的 java“echo”应用程序,它接受用户的输入并将其显示给他们以演示问题。我可以使用 IntelliJ 的内部“运行”命令毫无问题地运行此应用程序,也可以在执行由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 使这个应用程序工作?

【问题讨论】:

    标签: java gradle java.util.scanner build.gradle stdin


    【解决方案1】:

    你必须将默认标准输入连接到 gradle,把它放在 build.gradle 中:

    run {
        standardInput = System.in
    }
    

    更新:2021 年 9 月 9 日

    按照 cmets 中 nickbdyer 的建议,使用 --console plain 选项运行 gradlew run 以避免所有那些嘈杂和烦人的提示

    例子

    gradlew --console plain run
    

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

    例子

    gradlew -q --console plain run
    

    【讨论】:

    • 这很好用,对于任何对现在出现的丑陋提示感到恼火的人 gradle --console plain run 删除它。对此有一个未解决的问题issues.gradle.org/browse/GRADLE-1147,我在其中发现了sn-p。
    • 如果不使用应用程序插件,standardInput = System.in 行应该放在您正在运行的任何需要将标准输入重定向到它的任务中。对我来说,这是在自定义 JavaExec 任务中。
    • 老兄,它在我的运行脚本中不起作用。你能解释更多吗?
    • 你只是把那个sn-p放到build.gradle中然后输入gradle run,你得到了什么错误?
    • 在 org.gradle.api.Project 类型的根项目 上找不到参数 [build_70djsz9uqda5dtwfrqrhv32tu$_run_closure3@446452bb] 的方法 run()。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      我正在学习使用Gradle with Kotlin DSL,对我有用的答案得到了here before

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-13
        • 2017-05-03
        • 1970-01-01
        • 2015-04-01
        相关资源
        最近更新 更多