日期:2014-05-16 浏览次数:20738 次
import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; public class ExecuteCmd { /** * @param args */ public static void main(String[] args) { String[] commonds = {"sh","-c","export JAVA_HOME=/usr/java/jdk;echo $JAVA_HOME"}; RunSystemCommand(commonds, null); } public static void RunSystemCommand(String[] command, File file) { if (command != null && !command.equals("")) { try { Process ps = null; if (file != null) ps = Runtime.getRuntime().exec(command, null, file); else ps = Runtime.getRuntime().exec(command); String message = loadStream(ps.getInputStream()); String errorMeg = loadStream(ps.getErrorStream()); System.out.println(message); System.out.println("-------"); System.out.println(errorMeg); try { ps.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } private static String loadStream(InputStream in) throws IOException { int ptr = 0; in = new BufferedInputStream(in); StringBuffer buffer = new StringBuffer(); while ((ptr = in.read()) != -1) { buffer.append((char) ptr); } return new String(buffer.toString().getBytes("ISO-8859-1"), "GBK"); } }