How to execute shell script in Java?

简介: 经常需要在Java中调用其它的脚本(shell,cmd), 以前都用: Runtime r = Runtime.getSystemRuntime();r.exec("whatever you want to run");  但是有时侯其运行结果是不可预期的,带来很多麻烦。从java 5.0以后,引入了ProcessBuilder to create operating system

经常需要在Java中调用其它的脚本(shell,cmd), 以前都用:

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

目录
相关文章
|
4月前
|
Java Shell 分布式数据库
【大数据技术Hadoop+Spark】HBase数据模型、Shell操作、Java API示例程序讲解(附源码 超详细)
【大数据技术Hadoop+Spark】HBase数据模型、Shell操作、Java API示例程序讲解(附源码 超详细)
84 0
|
4月前
|
分布式计算 Java 大数据
【大数据技术Hadoop+Spark】HDFS Shell常用命令及HDFS Java API详解及实战(超详细 附源码)
【大数据技术Hadoop+Spark】HDFS Shell常用命令及HDFS Java API详解及实战(超详细 附源码)
210 0
|
1月前
|
Java 关系型数据库 MySQL
Java调用shell脚本实现数据库备份功能
本篇文章主要介绍怎样使用Java程序,执行服务器上的数据库备份Shell脚本进行MySQL数据库的备份功能。
|
5月前
|
Java Shell Linux
java执行脚本命令(shell脚本或cmd脚本)
java执行脚本命令(shell脚本或cmd脚本)
|
3月前
|
Java Shell 网络安全
java实现连接远程服务器,并可以执行shell命令
java实现连接远程服务器,并可以执行shell命令
56 2
|
4月前
|
SQL 分布式计算 Hadoop
【已解决[ERROR] Could not execute SQL statement. Reason:java.lang.ClassNotFoundException: org.apache.had
【已解决[ERROR] Could not execute SQL statement. Reason:java.lang.ClassNotFoundException: org.apache.had
83 0
|
9月前
|
搜索推荐 算法 Java
【算法】Shell排序的原理与Java实现
Shell排序,也称为希尔排序(Shell Sort),是一种改进的插入排序算法。它通过将待排序的数组分割成多个较小的子数组,对这些子数组进行插入排序,最后再对整个数组进行一次插入排序。希尔排序的核心思想是通过较大的间隔比较和交换元素,使得数组中的元素能够快速地朝最终位置前进,从而提高插入排序的效率。
66 0
|
11月前
|
分布式计算 Java Hadoop
Shell-通过shell启动Java类中的main方法 + 通过Shell启动jar包
Shell-通过shell启动Java类中的main方法 + 通过Shell启动jar包
566 0
|
Java Shell Linux
Java中运行shell脚本
Java中运行shell脚本
194 0
Java中运行shell脚本
|
Java Shell Maven
Java执行shell命令
java执行shell命令的方式有很多种,但是在应用的过程中,我们可能会遇上一些特殊的情况,导致执行脚本失败,不生效的场景。
346 0