好的,这是最终的解决方案。你需要把“过程阅读器到文件作家”的代码放到一个单独的线程,最后等待完成进程对象:
// 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文件的路径中存在空格!
您复制/粘贴到我认为的大部分命令。该命令将管道输出到文件。如果你通过Java调用它,那么你不这样做,你捕获该进程的输出并在Java代码中写入文件。 – Gimby
命令本身是正确的。但是你是对的,运行时库不支持该管道。我将尝试手动将过程输出写入文件。非常感谢! – salocinx
顺便说一句:管道响应。重定向在Linux上运行Runtime.exec(),我想也是在MacOS上。 – salocinx