Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

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

I have a created a simple java "echo" application that takes a user's input and shows it back to them to demonstrate the issue. I can run this application without trouble using IntelliJ's internal "run" command, and also when executing the compiled java file produced by gradle build. However, if I try to execute the application using gradle run, I get a NoSuchElementException thrown from the scanner.

I think gradle or the application plugin specifically is doing something strange with the system IO.

Application

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'
}

Any ideas how to make this application work using gradle run?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must wire up default stdin to gradle, put this in build.gradle:

run {
    standardInput = System.in
}

UPDATE: 9 Sep 2021

As suggested by nickbdyer in the comments run gradlew run with --console plain option to avoid all those noisy and irritating prompts

Example

gradlew --console plain run

And if you also want to completely get rid of all gradle tasks logs add -q option

Example

gradlew -q --console plain run

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...