如何从Java应用程序执行UNIX Shell脚本?

时间:2012-02-21 12:21:41

标签: java swing shell execute

有人知道如何从java应用程序执行shell脚本吗? 我正在使用win 7开发java应用程序,脚本文件在我的硬盘上。

3 个答案:

答案 0 :(得分:3)

希望这符合您的目的:

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

上面的代码将运行hello-world.sh文件中包含的脚本,它将在shell脚本控制台上显示输出。

答案 1 :(得分:1)

您可以在exec()课程中使用java.lang.Runtime系列方法。当然,如果不下载像MinGW或Cygwin这样的软件来支持它,你就无法在Windows机器上执行UNIX shell脚本(也许你的意思是当你的程序在另一台机器上运行时你将执行脚本。)

答案 2 :(得分:0)

首先,要在Windows 7系统上执行Unix shell脚本,您需要一个Unix shell。有几种可用的包括cygwin。假设你使用bash(最常见的是这些天),执行命令将bash -c scriptname来执行你的脚本。如果您只是执行Windows cmd或bat文件,则命令类似于cmd /c scriptname您应该检查cmd的帮助以验证这一点。

一旦开始这个过程,你需要立即启动一个线程来开始读取它的标准输出。您需要从流程中获取输出流并开始从中读取。如果不这样,两个进程之间的管道将填满,子进程将挂起。您还需要为子进程'stderr执行相同的操作,除非您在创建进程时使用该选项合并两个流。

相关问题