-3
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?

4

2 回答 2

2

由于您要运行的命令的路径包含空格,因此您需要在其周围加上引号:

String dumpCommand = "\"C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump\""+ " -u " + user +" -p" + " "+ database +" > "+path;         

编辑

AProcessBuilder将使这项工作更容易:

// 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具有许多其他功能(请参阅文档),包括为子进程定义环境变量、设置当前目录和重定向错误输出的能力。如果出现问题,后者在诊断问题时可能非常有用。

于 2013-07-15T05:27:59.207 回答
0

或者您可以使用 String.trim() 方法过滤掉空间。

于 2013-07-15T05:52:05.860 回答