从Windows 7中使用Runtime.getRuntime()。exec(cmd)调用“mysqldump”

时间:2014-07-22 12:50:59

标签: java mysql mysqldump runtime.exec

我试图通过以下方式在我的Java应用程序中转储MySQL数据库:

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”作为前缀。但它仍然无效。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

是的,你是对的,前几天我为从MySQL导出DataBase而上课了...... 您可以从控制台读取输出sream,然后写入文件

    String[] command = new String[] {"cmd.exe", "/c", "\"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump.exe\" --quick --lock-tables --user=\"root\" --password=\"mypwd\" mydatabase "};
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while ((line = input.readLine()) != null) {

        System.out.println(line); //there you can write file 
    }
    input.close();

最好的问候

答案 1 :(得分:2)

好的,这是最终的解决方案。您需要将“process-reader to file-writer”代码放入一个单独的线程中,最后等待进程对象完成:

    // 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文件的路径中使用空格!