Skip to content

Instantly share code, notes, and snippets.

@wyyqyl
Created June 24, 2016 03:53
Show Gist options
  • Save wyyqyl/e694dc0977b88b6a495d34fba73f1a19 to your computer and use it in GitHub Desktop.
Save wyyqyl/e694dc0977b88b6a495d34fba73f1a19 to your computer and use it in GitHub Desktop.
private static boolean isWindows() {
return System.getProperties().getProperty("os.name").contains("Windows");
}
public static String exec(String command, long timeout) {
Process ps;
try {
if(isWindows()) {
ps = Runtime.getRuntime().exec("cmd.exe /C " + command);
} else {
ps = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-cl", command});
}
} catch (IOException e) {
Logger.e("runtime.exec failed", e);
return null;
}
boolean stopped = false;
try {
stopped = ps.waitFor(timeout, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Logger.e("ps.waitFor interrupted", e);
}
if (!stopped) {
return null;
}
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
builder.append(line);
builder.append(Config.LINE_SEPARATOR);
}
} catch (IOException e) {
Logger.e("br.readLine failed", e);
return null;
}
return builder.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment