Execute .bat file from Java, why Eclips project-directory matters?
I want to execute a .bat
file from a Java program.
I declared the command for the .bat
like:
"cmd.exe", "/C", "Start", "C:\\File\\batfile.bat"
I use Windows XP and Eclipse Helios.
Code
String cmd;
try {
String[] command = { "cmd.exe", "/C", "Start", "C:\\File\\batfile.bat" };
Runtime r = Runtime.getRuntime();
Process p = r.exec(command);
p.wai开发者_运维技巧tFor();
} catch (Exception e)
{
System.out.println("Execution error");}
Why is it looking for my .bat
file in the project directory of Eclipse?
The process cmd.exe (picked from your PATH environment variable) is created with the current working directory the same as in the parent process (eclipse.exe = java). That is most likely c:\eclipse or the workspace dir.
If it cant find the file (C:\File\batfile.bat) it tries the current working dir. If you run this code using Run As Java try to change the working directory there. Also make sure the BAT file does exist.
Try this instead:
String com = System.getEnv("ComSpec") != null ? System.getEnv("ComSpec") : "C:\\Windows\\System32\\cmd.exe";
String[] command = { com, ...... }
ComSpec is often set to the path of cmd.exe. If not, use the full (expected path). You could also look for it in %SystemRoot%\system32. Or even %path%. But just checking ComSpec is better than using cmd.exe with nothing else by default.
As someone else pointed out, your default working directory when running from Eclipse is usually the Eclipse project folder.
It's generally good practice not to rely on the working folder being anything useful. Instead specify paths to anything needed, or search the path (if the app doesn't do so for you).
Remove Start
from the command - it's unnecessary - and try:
String[] command = { "cmd.exe", "/C", "C:\\File\\batfile.bat" };
Runtime.getRuntime().exec("cmd /c start C:\\File\\batfile.bat");
To ensure the execution of a specific file, provide the complete path instead of just the executable name (which will only run from context of where the JVM was started - possibly unexpected within some IDE):
try{
Runtime.getRuntime().exec(".bat file complete path");
} catch(IOException e) {
System.out.println("exception");
}
I faced the same scenario and following helped me to execute bat
successfully via java.
String[] commands = {"C:\\Windows\\System32\\cmd.exe", "/c", "bat_script_location.bat"};
Process process = Runtime.getRuntime().exec(commands, null, "output_directory_path");
process.waitFor();
int statusBatchJob = process.exitValue(); // to check the status of execution
精彩评论