有些时候,我们需要使用java来执行一些shell或者cmd命令,但是运行的时候可能会遇到一些问题,
比如:怎么获取返回值?怎么执行多条命令?为什么cd没有效果?
下面是我封装好的函数,可以直接使用。
函数封装
package com.alvin.util;import java.io.*;import java.util.ArrayList;import java.util.List;/*** cmd工具类** @author tianyunperfect*/public class CmdUtils {/*** 执行并返回结果** @param cmd* @return* @throws Exception*/public static String execute(String cmd) throws Exception {Process process = Runtime.getRuntime().exec(cmd);//获取返回值String line;StringBuilder sb = new StringBuilder();BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));while ((line = br.readLine()) != null) {System.out.println(line);sb.append(line + "\n");}br.close();return sb.toString();}/*** 批量执行cmd,并返回结果,默认当前目录* cd /home/test* pwd* rm -fr /home/proxy.log** @param commands* @return*/public static List<String> executeNewFlow(List<String> commands) throws Exception {List<String> rspList = new ArrayList<>();Runtime run = Runtime.getRuntime();Process proc = run.exec("/bin/bash", null, null);BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);for (String line : commands) {out.println(line);}// 这个命令必须执行,否则in流不结束。out.println("exit");String rspLine;while ((rspLine = in.readLine()) != null) {System.out.println(rspLine);rspList.add(rspLine);}proc.waitFor();in.close();out.close();proc.destroy();return rspList;}}
使用
执行单个命令,例如 ipconfig
execute("ipconfig")<<<<<<<<<<<<<<<< 结果Windows IP 配置无线局域网适配器 WLAN:连接特定的 DNS 后缀 . . . . . . . :本地链接 IPv6 地址. . . . . . . . : fe80::d443:f28e:ed86:d018%7IPv4 地址 . . . . . . . . . . . . : 10.200.9.73子网掩码 . . . . . . . . . . . . : 255.255.248.0默认网关. . . . . . . . . . . . . : 10.200.8.1…………
执行多个命令
ArrayList<String> strings = new ArrayList<>(Arrays.asList("pwd", "mkdir tmp", "cd tmp", "touch tmp.txt"));executeNewFlow(strings);<<<<<<<<<<<<<<<< 结果.└── tmp└── tmp.txt
