繁体中文
设为首页
加入收藏
当前位置:JSP技术首页 >> 资料/其它 >> Java中调用外部命令

Java中调用外部命令

2005-03-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:Java中调用外部命令 public class ExecCommond{ public ExecCommond(){} /** * 执行一条命令 * @param execStr String 命令字符串 * @return String 执行命令错误时的信息。 */ public static String exec(Stri...
关键字:外部 命令 Java

Java中调用外部命令

public class ExecCommond{

public ExecCommond(){}

/**

* 执行一条命令

* @param execStr String 命令字符串

* @return String 执行命令错误时的信息。

*/

public static String exec(String execStr) {

Runtime runtime = Runtime.getRuntime(); 取得当前运行期对象

String outInfo=""; //执行错误的输出信息

try {

String[] args = new String[] {"sh", "-c", execStr};//执行linux下的命令

//执行windows下的命令

// String[] args = new String[] {"cmd", "-c", execStr};

Process proc = runtime.exec(args); //启动另一个进程来执行命令

InputStream in = proc.getErrorStream();//得到错误信息输出。

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String line = "";

while ( (line = br.readLine())

!= null) {

outInfo = outInfo + line + "\n";

System.out.println(outInfo);

}

// 检查命令是否失败。

try {

if (proc.waitFor() != 0) {

System.err.println("exit value = " +

proc.exitValue());

}

}

catch (InterruptedException e) {

System.err.print(e);

e.printStackTrace();

}

}

catch (IOException e) {

flag = false;

System.out.println("exec error: " + e.getMessage());

e.printStackTrace();

}

finally {

return outInfo;

}

}

}

责任编辑:admin
相关文章