Java调用shell脚本并获得结果

Java代码
  1. /** 
  2.      * 运行shell脚本 
  3.      * @param shell 需要运行的shell脚本 
  4.      */  
  5.     public static void execShell(String shell){  
  6.         try {  
  7.             Runtime rt = Runtime.getRuntime();  
  8.             rt.exec(shell);  
  9.         } catch (Exception e) {  
  10.             e.printStackTrace();  
  11.         }  
  12.     }  
  13.   
  14.   
  15. /** 
  16.      * 运行shell 
  17.      *  
  18.      * @param shStr 
  19.      *            需要执行的shell 
  20.      * @return 
  21.      * @throws IOException 
  22.      */  
  23.     public static List runShell(String shStr) throws Exception {  
  24.         List strList = new ArrayList();  
  25.   
  26.         Process process;  
  27.         process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);  
  28.         InputStreamReader ir = new InputStreamReader(process  
  29.                 .getInputStream());  
  30.         LineNumberReader input = new LineNumberReader(ir);  
  31.         String line;  
  32.         process.waitFor();  
  33.         while ((line = input.readLine()) != null){  
  34.             strList.add(line);  
  35.         }  
  36.           
  37.         return strList;  
  38.     }  
/**
	 * 运行shell脚本
	 * @param shell 需要运行的shell脚本
	 */
	public static void execShell(String shell){
		try {
			Runtime rt = Runtime.getRuntime();
			rt.exec(shell);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


/**
	 * 运行shell
	 * 
	 * @param shStr
	 *            需要执行的shell
	 * @return
	 * @throws IOException
	 */
	public static List runShell(String shStr) throws Exception {
		List strList = new ArrayList();

		Process process;
		process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
		InputStreamReader ir = new InputStreamReader(process
				.getInputStream());
		LineNumberReader input = new LineNumberReader(ir);
		String line;
		process.waitFor();
		while ((line = input.readLine()) != null){
		    strList.add(line);
		}
		
		return strList;
	}

 

注:如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}写,才可以获得流


你可能感兴趣的:(Java基础)