How to execute shell script in Java?
2009-10-12 16:43
513 查看
经常需要在Java中调用其它的脚本(shell,cmd), 以前都用:
但是有时侯其运行结果是不可预期的,带来很多麻烦。从java 5.0以后,引入了ProcessBuilder to create operating system processes:
Runtime r = Runtime.getSystemRuntime(); r.exec("whatever you want to run");
但是有时侯其运行结果是不可预期的,带来很多麻烦。从java 5.0以后,引入了ProcessBuilder to create operating system processes:
String cmd = "cd ../.. ; ls -l"; // this is the command to execute in the Unix shell cmd ="cd ~/kaven/Tools/DART ; sh start_dart.sh"; // create a process for the shell ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); pb.redirectErrorStream(true); // use this to capture messages sent to stderr Process shell = pb.start(); InputStream shellIn = shell.getInputStream(); // this captures the output from the command int shellExitStatus = shell.waitFor(); // wait for the shell to finish and get the return code // at this point you can process the output issued by the command // for instance, this reads the output and writes it to System.out: int c; while ((c = shellIn.read()) != -1) { System.out.write(c); } // close the stream try { shellIn.close(); } catch (IOException ignoreMe) {} System.out.print(" *** End *** "+shellExitStatus); System.out.println(pb.command()); System.out.println(pb.directory()); System.out.println(pb.environment()); System.out.println(System.getenv()); System.out.println(System.getProperties());
相关文章推荐
- How to execute shell script in Java?
- How to run a Java Program as a daemon (service) on Linux (openSUSE) using a shell script
- How to find variable is empty in shell script
- how to execute sql script in c#
- How to format date for display or to use in a shell script
- How to create and execute JAR file in Java – Command line Eclipse Netbeans
- how to run 2 or more commands in a shell script [for Linux & Windows]
- How to find variable is empty in shell script
- [linux]How to set PATH in shell script, and keep it avaiable even after it exits
- [quote]HowTo Format Date For Display or Use In a Shell Script
- How to execute webject using java api in Windchill
- 【转】How to append current date and timestamp to filename in shell script
- How to use ftp in a shell script
- How To Execute Shell Command From Java
- How to Configure Selenium Webdriver in Eclipse and execute some simple test script.
- [quote] How to comment multi-lines in bash shell script.
- How to execute shell commands in C Part 1
- Java - How to change context root of a dynamic web project in eclipse
- How to use ArrayList in Java
- how to find shell type in linux