使用gradle run启动应用程序时,java.util.scanner会抛出NoSuchElementException

nic*_*yer 10 java stdin gradle java.util.scanner build.gradle

我创建了一个简单的java"echo"应用程序,它接受用户的输入并将其显示给他们以演示该问题.我可以使用IntelliJ的内部"运行"命令,以及执行由...生成的编译的java文件时运行此应用程序gradle build.但是,如果我尝试使用执行应用程序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);
  }
}
Run Code Online (Sandbox Code Playgroud)

的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'
}
Run Code Online (Sandbox Code Playgroud)

有关如何使用此应用程序的任何想法gradle run

Hum*_*iro 16

您必须将默认stdin连接到gradle,将其放在build.gradle中:

run{
    standardInput = System.in
}
Run Code Online (Sandbox Code Playgroud)

  • 这非常有用,对于那些因为丑陋的提示而烦恼的人,现在看来`gradle --console plain run`将其移除.有一个未解决的问题https://issues.gradle.org/browse/GRADLE-1147,我在那里找到了该片段. (4认同)
  • 在 org.gradle.api.Project 类型的根项目 <projectname> 上找不到参数 [build_70djsz9uqda5dtwfrqrhv32tu$_run_closure3@446452bb] 的方法 run()。 (4认同)
  • 如果不使用应用程序插件,`standardInput = System.in` 行应该放在你正在运行的需要将 stdin 重定向到它的任何任务中。对我来说,它在自定义 [JavaExec](https://docs.gradle.org/current/dsl/org.gradle.api.tasks.JavaExec.html) 任务中。 (3认同)