共计 1355 个字符,预计需要花费 4 分钟才能阅读完成。
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PyCmdUtil {
public static final String BLANK = " ";
public static final String ERROR = "error";
public static final String DATA = "data";
public static final Map<String, List<String>> executeCmd(String cmdPre, String... args) {Map map = new HashMap();
List errorList = new ArrayList();
List dataList = new ArrayList();
try {StringBuilder sb = new StringBuilder(cmdPre);
for (String arg : args) {sb.append(BLANK);
sb.append(arg);
}
System.out.println("executeCmd start:" + sb.toString());
Process process = Runtime.getRuntime().exec(sb.toString());
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String content = br.readLine();
while (content != null) {System.out.println(content);
dataList.add(content);
content = br.readLine();}
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
content = errorReader.readLine();
while (content != null) {System.out.println(content);
errorList.add(content);
content = br.readLine();}
} catch (IOException e) {e.printStackTrace();
}
map.put(ERROR, errorList);
map.put(DATA, dataList);
System.out.println("executeCmd result:" + JSON.toJSONString(map));
return map;
}
}
正文完