最近有个备份数据库的需求,需要用到Runtime.getRuntime().exec(command);各种百度,各种坑,最后耗时一天终于解决了,这里说一下坑,Centos7以上可能会遇到Runtime.getRuntime().exec(command).waitFor()=6的情况,这种情况就是无法执行shell命令。最后解决方案如下
try {
String sql = "/usr/bin/mysqldump -h"+hostIP+" -u"+userName+" -p"+password+" -t
"+databaseName+" "+tableName+" > "+savePath+fileName;
System.out.println(sql);
String[] commands = { "/bin/sh", "-c",sql};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(commands);
System.out.println("process.waitFor:"+process.waitFor());
if (process.waitFor() == 0) {// 0 表示线程正常终止。
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
重要的就是String[] commands = { "/bin/sh", "-c",sql};还好完美解决了,这里记录一下。