Java执行Linux命令并返回命令结果

andyzhaojianhui 2012-04-11

Java 可以通过 Runtime 调用Linux命令,形式如下:

Runtime.getRuntime().exec(command)

但是这样执行时没有任何输出,因为调用 Runtime.exec 方法将产生一个本地的进程,并返回一个Process子类的实例

(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例)该实例可用于控制进程或取得进程的相关信息。

由于调用 Runtime.exec 方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream() 方法重定向给它的父进程了。

用户需要用这些stream来向子进程输入数据或获取子进程的输出,下面的代码可以取到 linux 命令的执行结果:

try {
String[] cmd = new String[]{”/bin/sh”, “-c”, ” ls “};
Process ps = Runtime.getRuntime().exec(cmd);

BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append(”\n”);
}
String result = sb.toString();

System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}

 

 

package com.cisco.learning;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class Ys {

 public static void main(String[] args) throws IOException {

  Process exec = Runtime.getRuntime().exec("notepad");

  InputStream inputStream = exec.getInputStream();
  InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

  StringBuilder stringBuilder = new StringBuilder(10);
  try {

   String tmp;
   while ((tmp = bufferedReader.readLine()) != null) {
    stringBuilder.append(tmp);
   }

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   bufferedReader.close();

  }

  System.out.println(stringBuilder.toString());

 }

}


 

 


package com.cisco.learning;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class Ys {

 public static void main(String[] args) throws IOException {

  Process exec = Runtime.getRuntime().exec("notepad");

  InputStream inputStream = exec.getInputStream();
  InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

  StringBuilder stringBuilder = new StringBuilder(10);
  try {

   String tmp;
   while ((tmp = bufferedReader.readLine()) != null) {
    stringBuilder.append(tmp);
   }

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   bufferedReader.close();

  }

  System.out.println(stringBuilder.toString());

 }

}

相关推荐