使用到process和runtime兩個類,返回值通過process類的getinputstream()方法獲取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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
1
2
3
4
5
6
7
8
9
10
11
|
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命令并獲取執行結果的示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/arkblue/article/details/7897396