-1

I have a simple Windows batch file that calls Gradle:

@echo off
gradlew app:run

Gradle then runs a Java program:

plugins {
    application
}
application {
    mainClass.set("org.hertsig.MyApp")
}

The program reads from stdin. When I run the run task from IntelliJ directly, that works fine. But running it via the batch file, will not let the Java app see the input from stdin.

How do I connect stdin through my batch file?

Please note that this is about input to runtime-generated questions, so command line parameters, piping in a text file, or system properties will not do.

Windows 10, Gradle 7.2, Java 11.0.2

Jorn
  • 20,612
  • 18
  • 79
  • 126
  • Does this answer your question: https://discuss.gradle.org/t/how-can-i-execute-a-java-application-that-asks-for-user-input/3264/2 – akarnokd Jun 22 '22 at 19:28
  • Please provide more details, such as what Windows version, Gradle version, what's in the build.gradle. – akarnokd Jun 22 '22 at 19:37
  • Just to make sure, if you run `gradlew app:run` from `cmd.exe`, no outer bat file, does the input redirect work? – akarnokd Jun 22 '22 at 19:54
  • @akarnokd no, it doesn't redirect either when running from batch file or directly from cmd.exe – Jorn Jun 22 '22 at 19:55
  • All I could find and think of is that gradle config: https://stackoverflow.com/a/37737186/61158 – akarnokd Jun 22 '22 at 19:57

1 Answers1

0

I created a very basic program that echoes the user input via Gradle 7.4.2 (gradlew init):

package ConsoleApp1;

import java.util.Scanner;

public class App {
    public String getGreeting() {
        return "Hello World!";
    }

    public static void main(String[] args) {
        System.out.println(new App().getGreeting());
        
        Scanner scan = new Scanner(System.in);
        
        while (scan.hasNext()) {
            System.out.println("You typed: " + scan.next());
        }
    }
}

build.gradle

plugins {
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit:junit:4.13.2'

    // This dependency is used by the application.
    implementation 'com.google.guava:guava:30.1.1-jre'
}

application {
    // Define the main class for the application.
    mainClass = 'ConsoleApp1.App'
}

If I run as such: gradlew app:run, it just quits after printing Hello World!.

If I append

run {
   standardInput = System.in
}

and run it, I can provide console input:

c:\work\java\workspace\ConsoleApp1>gradlew app:run -q --console=plain
Hello World!
Y
You typed: Y
Z
You typed: Z

A bat file also works:

c:\work\java\workspace\ConsoleApp1>b.bat
Hello World!
Y
You typed: Y
Z
You typed: Z
akarnokd
  • 69,132
  • 14
  • 157
  • 192