Problem using Runtime.getRuntime().exec() in Linux terminal

I have a java source file which needs to execute this command in the terminal envrionment:

In window platform, when a run the program in Dos mode, it works fine.

Code:

Runtime.getRuntime().exec("cmd /c mysqldump -uxxx -pxxx -hxxx.xxx.xxx mydatabase | mysql -uxxx -pxxx -hxxx.xxx.xxx.xxx targetdatabase")

In linux platform, when I directly in the command mode, it works fine when I enter this command:

Code:

mysqldump -uxxx -pxxx -hxxx.xxx.xxx mydatabase | mysql -uxxx -pxxx -hxxx.xxx.xxx.xxx targetdatabase"

However, when I run the java program with

Code:

Runtime.getRuntime().exec("mysqldump -uxxx -pxxx -hxxx.xxx.xxx mydatabase | mysql -uxxx -pxxx -hxxx.xxx.xxx.xxx targetdatabase")

it didn't warn me but it failed.

Can anyone tell me how can I execute command in a Linux environment? Thx.

[865 byte] By [roamera] at [2007-11-27 5:52:25]
# 1
The command you entered is a shell command, so you need to start a shell (e.g. bash) and let it interpret the command (just like you did on Windows by saying "cmd").
quittea at 2007-7-12 15:43:24 > top of Java-index,Java Essentials,Java Programming...
# 2
maybe you should put the instruction in a .sh file and execute the .sh with exec()
calvino_inda at 2007-7-12 15:43:24 > top of Java-index,Java Essentials,Java Programming...
# 3

Since the pipe (the | ) needs to be interpreted by the shell you need

final String[] command =

{

"sh",

"-c",

"mysqldump -uxxx -pxxx -hxxx.xxx.xxx mydatabase | mysql -uxxx -pxxx -hxxx.xxx.xxx.xxx targetdatabase",

};

Process p = Runtime.getRuntime().exec(command);

Message was edited by:

sabre150

sabre150a at 2007-7-12 15:43:24 > top of Java-index,Java Essentials,Java Programming...
# 4

Thx and it succeed, and now I add one more argument for changing the file privileges:

chown apache:apache /home/myweb/http/www/member by this:

Runtime.getRuntime().exec( new String[]{ "bash", "-c", "mysqldump -uxxx -pxxx -hxxx.xxx.xxx mydatabase | mysql -uxxx -pxxx -hxxx.xxx.xxx.xxx targetdatabase", "chown apache:apache /home/myweb/http/www/member" } );

But I found that it failed, I read some doc on the web, some said we can't execute any os command such as dir/w, ls, rm. But they are not totally correct, I can use rm in the previous code.

So can we chown in this way?

roamera at 2007-7-12 15:43:24 > top of Java-index,Java Essentials,Java Programming...
# 5

Yes, I solved it, I found I just need to make another exec

Runtime.getRuntime().exec( new String[]{ "bash", "-c", "mysqldump -uxxx -pxxx -hxxx.xxx.xxx mydatabase | mysql -uxxx -pxxx -hxxx.xxx.xxx.xxx targetdatabase" } );

Runtime.getRuntime().exec( new String[]{ "bash", "-c", "chown -R apache:apache /home/mypath/http/www/member/"+Did} );

roamera at 2007-7-12 15:43:24 > top of Java-index,Java Essentials,Java Programming...