java调用shell命令并获取执行结果的示例
程序员文章站
2023-12-22 19:38:58
使用到process和runtime两个类,返回值通过process类的getinputstream()方法获取
package ark;
import...
使用到process和runtime两个类,返回值通过process类的getinputstream()方法获取
package ark; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.util.arraylist; import java.util.list; public class readcmdline { public static void main(string args[]) { process process = null; list<string> processlist = new arraylist<string>(); try { process = runtime.getruntime().exec("ps -aux"); bufferedreader input = new bufferedreader(new inputstreamreader(process.getinputstream())); string line = ""; while ((line = input.readline()) != null) { processlist.add(line); } input.close(); } catch (ioexception e) { e.printstacktrace(); } for (string line : processlist) { system.out.println(line); } } }
调用shell脚本,判断是否正常执行,如果正常结束,process的waitfor()方法返回0
public static void callshell(string shellstring) { try { process process = runtime.getruntime().exec(shellstring); int exitvalue = process.waitfor(); if (0 != exitvalue) { log.error("call shell failed. error code is :" + exitvalue); } } catch (throwable e) { log.error("call shell failed. " + e); } }
以上这篇java调用shell命令并获取执行结果的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。