__Note: This article was confirmed in the following environment. __
Suppose you have helloworld.bat
in a folder called C: \ sample
. The contents are as follows.
helloworld.bat
@echo off
echo Hello World 01
echo Hello World 02
echo Hello World 03
Below is a sample of executing this helloworld.bat
from Java.
//Generate ProcessBuilder
// helloworld.Connect stdin and stderr of bat to stdin and stderr of parent process.
var processBuilder = new ProcessBuilder("C:\\sample\\helloworld.bat");
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
//Process generation
// helloworld.Execute bat as a child process and stop the parent thread until the process finishes executing.
var process = processBuilder.start();
process.waitFor();
When you do this, you should see a string similar to the following in Java's standard output:
Hello World 01
Hello World 02
Hello World 03
__ Personally, the "addicted" point is the extension of the batch file. The extension of the file you want to execute must be bat or cmd. __
In the world of so-called shell scripts, there is no specification for the extension of the file in which the script is written. I think that it is customary to use sh
, but as long as you have execute permission, you can execute either txt
or html
, and there is no problem even if there is no extension.
On the other hand, in the Windows world, the extension is used to determine whether the file is a batch file. In other words, if the extension is bat or cmd, the file is regarded as an executable batch file.
What I was addicted to was "I tried to run a file with a non-extension bat or cmd with ProcessBuider
or Process
and it didn't work". I am a so-called open application developer. In that world (that is, Linux and Unix), if the execution authority is correctly granted, it can be executed regardless of the extension, so it is difficult to think that it is necessary to specify a specific extension. I didn't (´ ・ ω ・ `)
Recommended Posts