原文地址:
http://blog.csdn.net/xh16319/article/details/17302947
1 package scut.cs.cwh; 2 3 import java.io.InputStreamReader; 4 import java.io.LineNumberReader; 5 6 public class ExecLinuxCMD { 7 8 public static Object exec(String cmd) { 9 try { 10 String[] cmdA = { "/bin/sh", "-c", cmd }; 11 Process process = Runtime.getRuntime().exec(cmdA); 12 LineNumberReader br = new LineNumberReader( 13 new InputStreamReader(process 14 .getInputStream())); 15 StringBuffer sb = new StringBuffer(); 16 String line; 17 while ((line = br.readLine()) != null) { 18 System.out.println(line); 19 sb.append(line).append("\n"); 20 } 21 return sb.toString(); 22 } catch (Exception e) { 23 e.printStackTrace(); 24 } 25 return null; 26 } 27 28 public static void main(String[] args) { 29 // TODO Auto-generated method stub 30 String rst = exec("ls").toString(); 31 32 System.out.println(rst); 33 } 34 35 }
时间: 2024-10-07 15:42:29