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

拜拜、爱过 提交于 2019-12-29 06:14:24

问题


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?


回答1:


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

run{
    standardInput = System.in
}


来源:https://stackoverflow.com/questions/36723447/java-util-scanner-throws-nosuchelementexception-when-application-is-started-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!