[英]How do I execute UNIX Shell Scripts from a Java Application?
Does anybody know how to execute a shell script from java application? 有人知道如何从Java应用程序执行Shell脚本吗? I'm using win 7 to develop java application and the script file is on my hard disk. 我正在使用Win 7开发Java应用程序,并且脚本文件在硬盘上。
Hope this will serve your purpose: 希望这能达到您的目的:
import java.io.IOException;
import java.io.InputStream;
public class RunShellScript {
public static void runShellScript(String unixCommand) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", unixCommand);
processBuilder.redirectErrorStream(true);
Process shellProcess = processBuilder.start();
InputStream inputStream = shellProcess.getInputStream();
int consoleDisplay;
while((consoleDisplay=inputStream.read())!=-1) {
System.out.println(consoleDisplay);
}
try {
inputStream.close();
} catch (IOException iOException) { }
}
public static void main(String[] args) throws IOException, InterruptedException {
String unixCommand = "sh hello-world.sh";
runShellScript(unixCommand);
}
}
Above code will run the script included in hello-world.sh file and it will display the output on the shell script console. 上面的代码将运行hello-world.sh文件中包含的脚本,并将在shell脚本控制台上显示输出。
You would use the exec()
family of methods in the java.lang.Runtime
class. 您将在java.lang.Runtime
类中使用exec()
方法族。 Of course, you can't execute UNIX shell scripts on your Windows machine without downloading software like MinGW or Cygwin to support that (maybe you mean you're going to execute the script when your program runs on another machine.) 当然,如果不下载MinGW或Cygwin之类的软件来支持该程序,就无法在Windows机器上执行UNIX Shell脚本(也许这意味着当程序在另一台机器上运行时,您将要执行该脚本。)
First, to execute a Unix shell script on your Windows 7 system, you'd need a Unix shell. 首先,要在Windows 7系统上执行Unix Shell脚本,您将需要Unix Shell。 There are several available including cygwin. 有几种可用的,包括cygwin。 Assuming you go with bash (most common these days), the command to execute would be bash -c scriptname
to execute your script. 假设您使用bash(这是最近最常见的),要执行的命令将是bash -c scriptname
脚本名来执行脚本。 If you're just executing a Windows cmd or bat file the command is something like cmd /c scriptname
You should check the help for cmd to verify this. 如果您只是执行Windows cmd或bat文件,则该命令类似于cmd /c scriptname
您应该检查cmd的帮助以进行验证。
Once you start the process, you need to immediately start a thread to begin reading its stdout. 一旦开始该过程,就需要立即启动一个线程以开始读取其标准输出。 You need to get the output stream from the process and begin reading from it. 您需要从流程中获取输出流并开始从中读取。 If you don't the pipe between the two processes will fill up and the sub-process will hang. 如果不这样做,则两个进程之间的管道将填满,子进程将挂起。 You also need to do the same thing for the child process' stderr unless you use the option to merge the two streams when you create the process. 除非在创建流程时使用选项将两个流合并,否则还需要对子流程的stderr执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.