Reputation: 15389
I am running a Java application that executes a script. The relevant code is
String command [] = new String [2];
command[0] = "customSearch";
command[1] = query;
Process process = Runtime.getRuntime().exec(command);
This code runs on Linux because I placed a script called customSearch
in the /usr/bin
directory. In a similar way, I created a batch file in Windows called customSearch.bat
and made sure it is on the PATH
. However, this Java code will not work on Windows because "Batch files alone are not executable" as this thread mentions.
So to get it to work on Windows, I would have to say
command[0] = "cmd /c start customSearch";
However, I do not want to do this because this won't work on Linux. How can I run the batch file on Windows without changing command[0]
?
Upvotes: 0
Views: 1145
Reputation: 62864
You can add a check if the OS is Windows and then execute a custom-windows-batch-runner-snippet.
For example, I created a simple test.bat
file with a netstat
command within:
netstat
Here's how I executed it by a Java snippet:
String os = System.getProperty("os.name");
if (os.toLowerCase().indexOf("win") >= 0) {
command = new String[1];
command[0] = "test.bat";
Process process = Runtime.getRuntime().exec(command);
BufferedReader is = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = is.readLine()) != null) {
System.out.println(line);
}
}
This is the result in the console:
D:\workspace\SO>netstat
Active Connections
Proto Local Address Foreign Address State
TCP 127.0.0.1:19872 hp:49266 ESTABLISHED
TCP 127.0.0.1:49169 hp:49170 ESTABLISHED
TCP 127.0.0.1:49170 hp:49169 ESTABLISHED'
....
Even better, you can wrap every OS-specific command-executing snippets with if
statements.
Upvotes: 4