Java中的Runtime.getRuntime()。exec(),带有文件重定向

时间:2012-10-19 10:45:37

标签: java macos runtime.exec

  

可能重复:
  Redirection with Runtime.getRuntime().exec() doesn’t work

我正在尝试在OS X上运行带有Java的SQL脚本来启动我的数据库以进行测试。我知道这不是首选方法,但它是一种临时解决方案。

我试过阅读exec()函数,以及如何传递参数,但我根本无法使其工作。

我的代码如下所示:

try {
    Process p = Runtime.getRuntime().exec("/usr/local/mysql/bin/mysql -uroot dev_test <div/test_db.sql");

    p.waitFor();

    BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

    while ((line = input.readLine()) != null) {        
        System.out.println(line);
    }

    input.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

我也尝试在字符串数组中传递参数,但没有运气。

我已经设法通过使用这种格式使它在Windows机器上运行,但我无法更改它以便它在osx中​​工作:

Process p = Runtime.getRuntime().exec(new String[] { "cmd", "/C", "mysql -u root dev_test < div\\test_db.sql" });

1 个答案:

答案 0 :(得分:2)

更改代码以改为使用unix shell,就像在Windows解决方案中一样。结果代码如下所示:

String [] cmd = {"/bin/sh" , "-c", "/usr/local/mysql/bin/mysql -u root dev_test <div/test_db.sql"};
Process p = Runtime.getRuntime().exec(cmd);

谢谢,约阿希姆!对不起重新发布。