Skip to content
Advertisement

How to write a batch file that automatically gives input to a java program that prompts for user input

I would like to write a batch file that automatically gives input to a java program that prompts for user input.

My code so far is the following:

set path=C:Program FilesJavajdk-13.0.2bin

javac *.java

java myJavaProgram

The problem is that when myJavaProgram executes it prompts the user for input, so the batch file waits for me to give input in order to continue execution. I would like to be able to pass the input automatically, using the .bat. Is this possible? Thanks for any help!

EDIT: Updated question to include more context.

In more detail, when myJavaProgram is executed from the batch file, it prompts for user input from the console and waits for it. I must give a String. When I write the String, myJavaProgram reads it with a Scanner and does something with it (not important what it does). Then it terminates. I want to change the batch code so that I don’t need to write the String when it prompts for it. I want to set a variable with my input String in the batch file, and give this as input to myJavaProgram “bypassing” the console.

Advertisement

Answer

As suggested by @Mofi, a more straightforward solution uses the pipe | operator, that pipes the output from the first command (echo myString) into the input of the second command (java.exe myJavaProgram).

@echo off
If "%Path:~-1%" == ";" (Set "Path=%Path%%ProgramFiles%Javajdk-13.0.2bin") Else Set "Path=%Path%;%ProgramFiles%Javajdk-13.0.2bin"

javac.exe *.java

echo myString| java.exe myJavaProgram

Thank you for the help.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement