问题
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.
What I've Done
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.
What I'm Asking
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.
回答1:
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
.
回答2:
First, you should be using ProcessBuilder
to execute external programs, for an easier-to-use interface than Runtime.getRuntime().exec()
.
Second, to execute a .bat
file, all you have to do is execute cmd.exe
and pass the batch file name in the /C
option. Note that when you run a batch file you are starting a DOS cmd processor and telling it to run the batch file instead of reading from the terminal. Therefore, the batch file must be in a location that is accessible to cmd.exe
. Therefore it cannot be inside a jar file containing your Java program. If it is necessary to distribute it in the jar you will have to copy it to the filesystem somewhere.
来源:https://stackoverflow.com/questions/38024450/java-execute-external-windows-applications