Skip to content

Instantly share code, notes, and snippets.

@davidyang013
Created November 27, 2014 11:35
Show Gist options
  • Save davidyang013/4d262f7cdffb1eb42f88 to your computer and use it in GitHub Desktop.
Save davidyang013/4d262f7cdffb1eb42f88 to your computer and use it in GitHub Desktop.
Java execute shell script
package com.ericsson.iptv.testcase;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class ProcessUtil {
/**
*
* @param map
* store env variable<K,V>
* @param script
* arbitrary arguments, the first is script, the next is
* arguments
* @return 0 represent normal
*/
public static int execute(Map<String, String> map, String... arguments) {
ProcessBuilder pb = new ProcessBuilder(arguments);
Map<String, String> env = pb.environment();
for (Map.Entry<String, String> entry : map.entrySet()) {
env.put(entry.getKey(), entry.getValue());
}
Process p = null;
try {
p = pb.start();
if (p != null) {
p.waitFor();
}
BufferedReader br = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
p.destroy();
}
System.out.println(p.exitValue());
return p.exitValue();
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("JAVA_HOME",
"/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home");
map.put("NODE_PATH", "/usr/local/lib/node_modules/");
String script = "/Users/david/Documents/workspace/Cable/src/main/java/com/ericsson/iptv/testcase/test.sh";
execute(map, script);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment