简体   繁体   中英

How do I execute UNIX Shell Scripts from a Java Application?

Does anybody know how to execute a shell script from java application? I'm using win 7 to develop java application and the script file is on my hard disk.

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.

You would use the exec() family of methods in the java.lang.Runtime class. 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.)

First, to execute a Unix shell script on your Windows 7 system, you'd need a Unix shell. There are several available including cygwin. Assuming you go with bash (most common these days), the command to execute would be bash -c scriptname to execute your script. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM