java运行linux命令2
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class ShellUtil {
private static String execCmd(String cmd){
StringBuilder result = new StringBuilder();
String[] cmds = new String[0];
Charset charset= StandardCharsets.UTF_8;
// if(SystemUtil.isWindows()){
// cmds=new String[]{"cmd.exe","/C",cmd};
// charset=Charset.forName("GBK");
// }else if(SystemUtil.isLinux()){
cmds=new String[]{"sh","-c",cmd};
// }
BufferedReader br = null;
Process p;
try {
p = Runtime.getRuntime().exec(cmds);
br = new BufferedReader(new InputStreamReader(p.getInputStream(),charset));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
} catch (Exception ignored) {
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception ignored) {
}
}
}
return result.toString();
}
public static void main(String[] args) {
String cmd = "ps -ef|grep java";
String ret = execCmd(cmd);
System.out.println(ret);
}
}
原文地址:https://blog.csdn.net/daqinzl/article/details/143584038
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!