As suggested by many here on SO
, Runtime.getRuntime().exec(..)
might give troubles. Instead use ProcessBuilder
API.
I used the following:
public static void run(String argument) throws IOException {
List<String> command = new ArrayList<String>();
OsCheck.OSType osType = OsCheck.getOperatingSystemType();
System.out.println("OS: " + osType);
String shell;
if(osType.toString().equals("Windows")) {
command.add("cmd.exe");
command.add("/c");
} else {
shell = "/bin/bash";
command.add(shell);
}
command.add(argument);
InputStream inputStream = null;
InputStream errorStream = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
inputStream = process.getInputStream();
errorStream = process.getErrorStream();
System.out.println("Process InputStream: " + IOUtils.toString(inputStream, "utf-8"));
System.out.println("Process ErrorStream: " + IOUtils.toString(errorStream, "utf-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream .close();
}
if (errorStream != null) {
errorStream.close();
}
}
}
Utility:
public final class OsCheck {
/**
* Enum type which contains OS names.
*/
private static OSType detectedOS;
/**
* <p>
* Finds the OS
* </p>
*
* @return One of the values of the enum OSType
*/
public static OSType getOperatingSystemType() {
if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase();
if (OS.contains("win")) {
detectedOS = OSType.Windows;
} else if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedOS = OSType.MacOS;
} else {
detectedOS = OSType.Linux;
}
}
return detectedOS;
}
/**
* Represents the popular os types i.e Windows, or MacOS or Linux
*/
public enum OSType {
Windows, MacOS, Linux
}
}