0

Possible Duplicate:
Redirection with Runtime.getRuntime().exec() doesn’t work

I'm trying to run a SQL script with Java on OS X to initiate my database for testing. I know it's not the preferred way to do it, but it's a temporary solution.

I've tried to read about the exec() function, and how to pass parameters, but I simply can't make it work.

My code looks like this:

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

I've also tried to pass the arguments in a string array, but with no luck.

I've managed to make it run on a windows machine by using this format, but I can't change it so that it works in osx:

Process p = Runtime.getRuntime().exec(new String[] { "cmd", "/C", "mysql -u root dev_test < div\\test_db.sql" });
Community
  • 1
  • 1
Skovly
  • 234
  • 1
  • 8
  • 22
  • Yeah, noticed that solution. But figured it might be different since it's redirecting output and not input? – Skovly Oct 19 '12 at 10:57
  • 1
    It's not really different, because redirecting output and input is both handled by the shell, so you'll have to do both manually (or invoke the shell explicitly) for it to work. Explicitly invoking the shell is actually what your Windows solution does (where `cmd.exe` is the shell). – Joachim Sauer Oct 19 '12 at 11:00
  • Thanks, Joachim. I changed it to use a unix shell (bin/sh) the same way as the windows solution. Worked perfectly. Thanks! – Skovly Oct 19 '12 at 11:10

1 Answers1

2

Changed the code to use a unix shell instead, as in the Windows solution. The resulting code looks like this:

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

Thanks, Joachim! Sorry for repost.

Skovly
  • 234
  • 1
  • 8
  • 22