0

可能重复:
使用 Runtime.getRuntime().exec() 重定向不起作用

我正在尝试在 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" });
4

1 回答 1

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);

谢谢,约阿希姆!很抱歉重新发布。

于 2012-10-19T11:15:25.050 回答