java Runtime如何執(zhí)行多條命令
使用 && 分隔命令
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
30
|
public static void cmd() { String ls = " cd /home/ && dir " ; Process process = null ; String cmd = getOsCmd()+ ls; try { process = Runtime.getRuntime().exec(cmd); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line = null ; while ((line = bufferedReader.readLine()) != null ) { System.out.println( new String(line.getBytes(), "GBK" )); } } catch (Exception e){ e.printStackTrace(); } finally { process.destroy(); } } public static String getOsCmd(){ Properties props=System.getProperties(); //獲得系統(tǒng)屬性集 String osName = props.getProperty( "os.name" ); //操作系統(tǒng)名稱 if (osName.toLowerCase().contains( "linux" )){ return "/bin/sh -c" ; } else if (osName.toLowerCase().contains( "windows" )){ return "cmd /c" ; } else { throw new RuntimeException( "服務(wù)器不是linux|windows操作系統(tǒng)" ); } } |
Runtime.getRuntime().exec 執(zhí)行多條
中間加上 & 或者 && 就可以執(zhí)行多條了.
1
2
3
|
Runtime.getRuntime().exec( "cmd1 && " + "cmd2 && " + "cmd3 && " ); |
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/lanlianhua_luffy/article/details/106694469