java equivalent for system() command in perl
Can I use Runtime to achieve the same? If so what are the pros/cons I have to invoke a shell script from java.
Thanks in advance开发者_JAVA技巧.
You can use Runtime.exec()
to execute a shell script from Java. Of course this will make it less cross-platform and harder to maintain. If you want to wait for the shell script to finish you need to use the Process object returned by exec()
and call waitFor()
. You can also get the stdin/out/err
which is very useful. You might also want to explicitly call the correct shell e.g. exec("sh script.sh")
.
Yes, use Runtime.exec()
.
Runtime.getRuntime().exec("command param param");
I don't understand pros/cons. This works. If you need to execute a shell script from java, you should use this.
Runtime.getRuntime().exec("the_script.sh");
The new process will inherit the environment of the Java process.
If you need more control about creation of the process, ProcessBuilder is a more powerful alternative to Runtime.exec(...)
.
精彩评论