问题描述
我正尝试通过以下方式在Java应用程序中转储MySQL数据库:
I am trying to dump a MySQL database within my Java application the following way:
String[] command = new String[] {"cmd.exe", "/c", "C:/mysql/mysqldump.exe" --quick --lock-tables --user=\"root\" --password=\"mypwd\" mydatabase > \"C:/mydump.sql\""};
Process process = Runtime.getRuntime().exec(command);
int exitcode = process.waitFor();
该过程失败,退出代码为6.我在某处读取到操作数>"的解释不正确,并且提示使用"cmd.exe/c"作为前缀.但这仍然行不通.
The process fails with exit-code 6. I somewhere read that the operand ">" is not correctly interpreted and there was the hint to use "cmd.exe /c" as prefix. But it still doesn't work.
有什么想法吗?
推荐答案
好的,这是最终解决方案.您需要将进程读取器到文件写入器"代码放入单独的线程中,最后等待进程对象完成:
Okay here's the final solution. You need to put the "process-reader to file-writer" code into a separate thread and finally wait for the process object to be finished:
// define backup file
File fbackup = new File("C:/backup.sql");
// execute mysqldump command
String[] command = new String[] {"cmd.exe", "/c", "C:/path/to/mysqldump.exe --quick --lock-tables --user=myuser --password=mypwd mydatabase"};
final Process process = Runtime.getRuntime().exec(command);
// write process output line by line to file
if(process!=null) {
new Thread(new Runnable() {
@Override
public void run() {
try{
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(process.getInputStream())));
BufferedWriter writer = new BufferedWriter(new FileWriter(fbackup))) {
String line;
while((line=reader.readLine())!=null) {
writer.write(line);
writer.newLine();
}
}
} catch(Exception ex){
// handle or log exception ...
}
}
}).start();
}
if(process!=null && process.waitFor()==0) {
// success ...
} else {
// failed
}
在Linux上,您可以像往常一样使用>"将命令的输出直接重定向到文件...(以及我认为在Mac OS X上).因此不需要线程.通常,请避免在mysqldump/mysqldump.exe文件的路径中出现空格!
On Linux you can directly re-direct the output of the command to a file by using ">" as usual... (and also on Mac OS X I think). So no need for the thread. Generally, please avoid white spaces in your path to the mysqldump/mysqldump.exe file!
这篇关于调用"mysqldump".使用Windows 7中的Runtime.getRuntime().exec(cmd)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!