I'm unsure how to start an external application (specifically on Windows) through Java code. I'm not planning on using this Java code for Mac/Linux, so let's focus on the Windows code.
I've been researching this question for the last two days, and I still have not found an answer. I easily found the Runtime.getRuntime().exec()
method, but the thing is I cannot find information on launching a Batch (.bat) file from my local workspace in IntelliJ Idea.
I would just like to know how to execute a local Batch file in my workspace (at a folder like com.example.batch
) and/or how to execute a (.exe) or (.bat) with the direct file address. (For example the Defragment and Optimize Drives (.exe) for Windows: C:\WINDOWS\system32\dfrgui.exe
)
Thanks to all in advance, I've been dying for this answer.
Have you read the essential Runtime.exec() article?
Page 2 of this article lists a common pitfall: Runtime.exec() is not a command line.
.bat files are not executables. They are collections of instructions. Like shell scripts in Linux, you need something to actually execute these instructions.
Your executable in this case is cmd.exe
, which will take /C
and com.example.batch
as its arguments:
Runtime.getRuntime().exec(new String[] { "cmd.exe", "/C", "com.example.batch"});
As a side note, check out the ProcessBuilder
class. It's much nicer than Runtime
. And yes, all the rules in the Runtime
article apply to ProcessBuilder
.