我正在使用ProcessBuilder
从java代码执行mysqldump
这是我的代码
public static void executeCommant(String... command) throws Exception {
ProcessBuilder processBuilder = null;
processBuilder = new ProcessBuilder(command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
int resultCode = process.waitFor();
if (resultCode != 0) {
throw new Exception("" + readCommandOutput(process.getInputStream()));
}
}
private static String readCommandOutput(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
executeCommant("mysqldump -u root -P 3316 -h localhost > G:\\test.sql");
}
问题是我得到以下异常,即使我从cmd运行相同的命令我没有任何问题,我只是无法弄清楚为什么它找不到指定的文件! PS:我试图给出mysqldump.exe的完整路径并得到相同的结果
Exception in thread "main" java.io.IOException: Cannot run program "mysqldump -u root -P 3316 -h localhost > G:\test.sql": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:470)
at com.etq.e2mc.platform.windows.WindowsProcess.executeCommant(WindowsProcess.java:46)
at com.etq.e2mc.platform.windows.WindowsProcess.main(WindowsProcess.java:67)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:177)
at java.lang.ProcessImpl.start(ProcessImpl.java:28)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 2 more
答案 0 :(得分:2)
首先,您使用数组调用ProcessBuilder(String... command)
,这意味着数组的第一个值是程序。但是,您要发送整个字符串"mysqldump -u root -P 3316 -h localhost > G:\\test.sql"
,而这不是程序。只有mysqldump
是该计划。
其次,在使用getInputStream()
捕获输出时,您需要在调用waitFor()
之前执行,否则您的输出缓冲区运行完全风险,停止执行您的程序#39;重新运行,主要导致等待命令退出的程序和等待您读取输出的命令之间的死锁。如果您需要流,通常需要在单独的线程中阅读它。
第三,您无法在命令字符串中使用>
重定向输出。这是cmd.exe
的作用,您不会调用cmd.exe
。由于您要重定向到文件,请使用ProcessBuilder
直接执行此操作。
ProcessBuilder processBuilder = new ProcessBuilder(
"mysqldump", "-u", "root", "-P", "3316", "-h", "localhost");
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(new File("G:\\test.sql"));
Process process = processBuilder.start();
int resultCode = process.waitFor();
if (resultCode != 0) {
throw new Exception("Program failed with error " + resultCode);
}