Runtime.getRuntime().exec(...)使用方法

如果想要了解更多的信息,参阅代码里面给的链接 



下面是这个正确的例子

  1. public class RuntimeExec {
  2. /**
  3. * Runtime execute.
  4. *
  5. * @param cmd the command.
  6. * @return success or failure
  7. * @see {@link http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4}
  8. * @since 1.1
  9. */
  10. public static boolean runtimeExec(String cmd) {
  11. try {
  12. Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
  13. // any error message?
  14. StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
  15. // any output?
  16. StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
  17. ) {
  18. System.err.println("执行\"" + cmd + "\"时返回值=" + proc.exitValue());
  19. return false;
  20. else {
  21. return true;
  22. }
  23. catch (Exception e) {
  24. e.printStackTrace();
  25. return false;
  26. }
  27. }
  28. static class StreamGobbler extends Thread {
  29. InputStream is;
  30. String type;
  31. StreamGobbler(InputStream is, String type) {
  32. this.is = is;
  33. this.type = type;
  34. }
  35. public void run() {
  36. try {
  37. InputStreamReader isr = new InputStreamReader(is);
  38. BufferedReader br = new BufferedReader(isr);
  39. String line = null;
  40. while ((line = br.readLine()) != null)
  41. System.out.println(type + ">" + line);
  42. catch (IOException ioe) {
  43. ioe.printStackTrace();
  44. }
  45. }
  46. }
  47. }
04-14 14:08