有时候我们在Linux中运行Java程序时,需要调用一些Shell命令和脚本。而Runtime.getRuntime().exec()方法给我们提供了这个功能,而且Runtime.getRuntime()给我们提供了以下几种exec()方法:
Process exec(String command)
在单独的进程中执行指定的字符串命令。
Process exec(String[] cmdarray)
在单独的进程中执行指定命令和变量。
Process exec(String[] cmdarray, String[] envp)
在指定环境的独立进程中执行指定命令和变量。
Process exec(String[] cmdarray, String[] envp, File dir)
在指定环境和工作目录的独立进程中执行指定的命令和变量。
Process exec(String command, String[] envp)
在指定环境的单独进程中执行指定的字符串命令。
Process exec(String command, String[] envp, File dir)
在有指定环境和工作目录的独立进程中执行指定的字符串命令。
细心的读者会发现,为了执行调用操作,JVM会启一个Process,所以我们可以通过调用Process类的以下方法,得知调用操作是否正确执行:
abstract int waitFor()
导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。
另外,调用某些Shell命令或脚本时,会有返回值,那么我们如果捕获这些返回值或输出呢?为了解决这个问题,Process类提供了:
abstract InputStream getInputStream()
获取子进程的输入流。 最好对输入流进行缓冲。
这里为了说明问题,我仅用tar命令进行演示。tar命令是一个打包而不进行压缩的命令。同时,为了检查tar的调用是否被正常执行,我将调用waitFor()方法。
private void callCMD(String tarName, String fileName, String... workspace){
try {
String cmd = "tar -cf" + tarName + " " + fileName;
// String[] cmd = {"tar", "-cf", tarName, fileName};
File dir = null;
if(workspace[0] != null){
dir = new File(workspace[0]);
System.out.println(workspace[0]);
}
process = Runtime.getRuntime().exec(cmd, null, dir);
// process = Runtime.getRuntime().exec(cmd);
int status = process.waitFor();
if(status != 0){
System.err.println("Failed to call shell's command and the return status's is: " + status);
}
}
catch (Exception e){
e.printStackTrace();
}
}
String[] cmd = {"tar", "-cf", tarName, fileName}; //right
String[] cmd = {"tar -cf", tarName, fileName}; //error
/root/workspace/eclipse/Test/src/edu/wzm/CallShell.java
/root/experiment/hive
call.callCMD("/root/experiment/hive.tar", "/root/experiment/hive", null);
// OR
call.callCMD("/root/experiment/hive.tar", "/root/experiment/hive");
call.callCMD("hive.tar", "hive", "/root/experiment/");
Java调用Shell命令和调用Shell脚本的操作一模一样。我这里介绍另外几个方面:
给脚本传递参数,这个操作很简单,无非是把参数加到调用命令后面组成String,或String[]。
捕获调用输出信息,前面也提到过用Process.getInputStream()。不过,建议最好对输入流进行缓冲:
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
val=2
call=Bash Shell
#!/usr/bin/env bash
args=1
if [ $# -eq 1 ];then
args=$1
echo "The argument is: $args"
fi
echo "This is a $call"
start=`date +%s`
sleep 3s
end=`date +%s`
cost=$((($end - $start) * $args * $val))
echo "Cost Time: $cost"
private void callScript(String script, String args, String... workspace){
try {
String cmd = "sh " + script + " " + args;
// String[] cmd = {"sh", script, "4"};
File dir = null;
if(workspace[0] != null){
dir = new File(workspace[0]);
System.out.println(workspace[0]);
}
String[] evnp = {"val=2", "call=Bash Shell"};
process = Runtime.getRuntime().exec(cmd, evnp, dir);
// process = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CallShell call = new CallShell();
call.callScript("test.sh", "4", "/root/experiment/");
}
/root/experiment/
The argument is: 4
This is a Bash Shell
Cost Time: 24