java调用Command命令

时间:2023-11-09 21:45:14

-----------

import java.io.BufferedReader;
import java.io.InputStreamReader; /**
* 此类用来执行Command命令
*
* @author zhj
*
*/
public class CommandHelper {
private boolean execCommand(String cmd) {
Process process = null;
BufferedReader br = null;
try {
process = Runtime.getRuntime().exec(cmd);
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
return false;
} finally {
try {
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
} public static void main(String[] args) {
CommandHelper mCommandHelper = new CommandHelper();
mCommandHelper.execCommand("ls /opt");
}
}

--