String dumpCommand = "C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump" + " -u " + user + " -p" + " " + database + " > " + path;
Runtime rt = Runtime.getRuntime();
File test = new File(path);
PrintStream ps;
try{
Process child = rt.exec(dumpCommand);
System.out.println("Child" + child);
ps = new PrintStream(test);
InputStream in = child.getInputStream();
int ch;
while ((ch = in.read()) != -1) {
ps.write(ch);
System.out.write(ch);
}
}
代码无效。它无限运行?如何在java上运行mysqldump?
答案 0 :(得分:2)
由于您要运行的命令的路径包含空格,因此需要围绕它的引号:
String dumpCommand = "\"C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump\""+ " -u " + user +" -p" + " "+ database +" > "+path;
修改强>
ProcessBuilder
会让这项工作更轻松:
// Step 1: set up the command line
ProcessBuilder pb = new ProcessBuilder(
"C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump",
"-u",
user,
"-p"
database);
// Step 2: redirect output
File test = new File(path);
pb.redirectOutput(test);
// Step 3: start the process
Process proc = pb.start();
ProcessBuilder
类具有许多其他功能(请参阅文档),包括为子进程定义环境变量,设置当前目录和重定向错误输出的功能。如果出现问题,后者可能对诊断问题非常有用。
答案 1 :(得分:0)
或者您可以使用String.trim()方法过滤掉空格。