如何在java程序中调用linux命令或者shell脚本

2025-05-13 15:49:21
推荐回答(2个)
回答(1):

public static String execShell(String shellString){
System.out.println("将要执行的shell语句是:   "+shellString);
String isOK="ok";
try{
Process process=Runtime.getRuntime().exec(shellString);

BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line="";
while((line = input.readLine()) != null){
System.out.println(line);
}
input.close();
int exitValue=process.waitFor();
if(0!=exitValue){
isOK="no";
System.err.println("call shell failed.errorcodeis:"+exitValue);
}
}catch(Throwable e){
e.printStackTrace();
}

return isOK;
}

这是我在java中用过的一个调用shell的函数,你可以试试;执行成功返回ok,执行失败返回no

回答(2):

Runtime.exec()

~
~
~