今天在linux环境下需要做一个简单的测试,使用java调用bash命令。
源码
public class HelloWorld {
private String helloMsg = "Hello World!";
private static String cmd = "/root/test/1.sh";
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
execCommand(cmd);
}
public HelloWorld() {
System.out.println(helloMsg);
}
public static boolean execCommand(String cmd) {
Process process = null;
try {
process = Runtime.getRuntime().exec(cmd);
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
process.destroy();
} catch (Exception e) {
}
}
return true;
}
}
编译
javac HelloWorld.java
运行
java HelloWorld