Java Shell Command runCommand(String cmd)

Here you can find the source of runCommand(String cmd)

Description

Calls runCommand/2 assuming that wait=true.

License

Apache License

Parameter

Parameter Description
cmd The string containing the command to execute

Declaration

public static void runCommand(String cmd) 

Method Source Code


//package com.java2s;
//  Licensed under the Apache License, Version 2.0 (the "License");

import java.io.*;

public class Main {
    /**/*from   w  w  w .  j  av  a  2  s. c o m*/
     * Calls runCommand/2 assuming that wait=true.
     *
     * @param  cmd  The string containing the command to execute
     */
    public static void runCommand(String cmd) {
        runCommand(cmd, true);
    }

    /**
     * Run a command with the option of waiting for it to finish.
     *
     * @param  cmd  The string containing the command to execute
     * @param  wait True if the caller should wait for this thread to 
     *              finish before continuing, false otherwise.
     */
    public static void runCommand(String cmd, boolean wait) {
        try {
            System.out.println("Running command: " + cmd);
            Process proc = Runtime.getRuntime().exec(cmd);

            // This needs to be done, otherwise some processes fill up
            // some Java buffer and make it so the spawned process
            // doesn't complete.
            BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));

            String line = null;
            while ((line = br.readLine()) != null) {
                // while (br.readLine() != null) {
                // just eat up the inputstream

                // Use this if you want to see the output from running
                // the command.
                System.out.println(line);
            }

            if (wait) {
                try {
                    proc.waitFor();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            proc.getInputStream().close();
            proc.getOutputStream().close();
            proc.getErrorStream().close();
        } catch (IOException e) {
            System.out.println("Unable to run command: " + cmd);
        }
    }
}

Related

  1. getJavaVersion(String command)
  2. runCommand(final ProcessBuilder command)
  3. runCommand(String cmd)
  4. runCommand(String command)
  5. runCommand(String command)
  6. runCommand(String command, String args, String file)