Possible Duplicate:
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" });
最佳答案
将代码更改为使用 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);
谢谢,约阿希姆!抱歉重新发帖。
关于java - Java 中的 Runtime.getRuntime().exec() 具有文件重定向功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972619/