Michele De Pascalis
Michele De Pascalis

Reputation: 952

Gradle run task accepts input when run in console, but not as an IDEA run configuration

I have the following Java main class which I am trying to compile and run using the Gradle plugin in IntelliJ IDEA:

package com.mikidep.bookshop;

import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        System.out.print("Inserisci testo qui: ");
        System.out.println(in.nextLine());
        System.out.println("Yee!");
    }
}

My build.gradle follows:

group 'com.mikidep.bookshop'
version '1.0-SNAPSHOT'

apply plugin: 'application'

mainClassName = "com.mikidep.bookshop.Main"

sourceCompatibility = 1.5

repositories {
    mavenCentral()
}

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

run {
    standardInput = System.in
}

Now if I run gradle run -q in a terminal everything works as expected. However there is this IDEA run configuration that I would like to use to test-run:

IDEA Run configuration

Everything is fine until I do some console input. in.nextLine() throws the following exception:

Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1585) at com.mikidep.bookshop.Main.main(Main.java:10)

I also tried to debug it and noticed that all fields in System.in seem zeroed out, like the whole stream hadn't been initialized. Anyone knows what's happening?

EDIT: I just verified that this affects the build script as well: I added this lines to the run task

System.out.println("Wait...")
System.in.read()
System.out.println("Ok!")

But Gradle prints those two lines right away, without waiting for my input.

Upvotes: 7

Views: 5497

Answers (1)

JBaruch
JBaruch

Reputation: 22923

System.in is not the Script parameters.

In command line, since you don't specify any parameters that Gradle expects, it just uses the remaining of what you typed as standard input. In IDEA the standard input and the script parameters are separated and the standard input comes from the run or debug console window.

Upvotes: 2

Related Questions