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

Java中带有文件重定向的Runtime.getRuntime().exec(),java,macos,runtime.exec,Java,Macos,Runtime.exec,可能重复: 我正试图在OSX上运行一个带有Java的SQL脚本来启动数据库进行测试。我知道这不是最好的方法,但这是一个暂时的解决办法 我试图阅读有关exec()函数的内容,以及如何传递参数,但我就是无法让它工作 我的代码如下所示: try { Process p = Runtime.getRuntime().exec("/usr/local/mysql/bin/mysql -uroot dev_test <div/test_db.sql"); p.waitFor();

可能重复:

我正试图在OSX上运行一个带有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();
    }
}
String [] cmd = {"/bin/sh" , "-c", "/usr/local/mysql/bin/mysql -u root dev_test <div/test_db.sql"};
Process p = Runtime.getRuntime().exec(cmd);
试试看{

Process p=Runtime.getRuntime().exec(“/usr/local/mysql/bin/mysql-uroot dev_test将代码改为使用unix shell,如Windows解决方案中所示。生成的代码如下所示:

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

String[]cmd={”/bin/sh“,“-c”,“/usr/local/mysql/bin/mysql-u root dev_test是的,注意到了这个解决方案。但我想它可能会有所不同,因为它重定向输出和不重定向输入?其实并没有什么不同,因为重定向输出和输入都是由shell处理的,所以您必须手动执行这两个操作(或显式调用shell)使其工作。显式调用shell实际上就是您的Windows解决方案所做的(其中
cmd.exe
是shell)。谢谢,Joachim。我将其更改为使用与Windows解决方案相同的unix shell(bin/sh)。工作非常好。谢谢!