Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process with the specified environment and working directory.

Usage

From source file:Main.java

public static void main(String[] args) {
    try {/*from   ww  w .j av  a2 s.co m*/

        File dir = new File("C:/");

        String[] envArray = new String[2];
        envArray[0] = "";
        envArray[1] = "";
        // create a process and execute notepad.exe and currect environment

        Runtime runTime = Runtime.getRuntime();
        Process process = runTime.exec("notepad.exe", envArray, dir);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:Main.java

public static void main(String[] args) {
    try {/*from w w  w .  j a v  a 2 s  .  co m*/
        String[] cmdArray = new String[2];
        // the program to open
        cmdArray[0] = "notepad.exe";

        // txt file to open with notepad
        cmdArray[1] = "test.txt";

        File dir = new File("c:/");

        String[] envArray = new String[2];
        envArray[0] = "";
        envArray[1] = "";

        Runtime runTime = Runtime.getRuntime();

        Process process = runTime.exec(cmdArray, envArray, dir);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:org.apache.cloudstack.network.contrail.management.TestDbSetup.java

public static void initCloudstackDb() throws Exception {
    try {/*  ww  w.j  a  va2 s .co  m*/
        File dir = new File("../../../");
        Runtime r = Runtime.getRuntime();
        Process process = r.exec("mvn -P developer -pl developer -Ddeploydb ", null, dir);
        dumpProcessOutput(process);
        process.waitFor();
    } catch (Exception e) {
        String cause = e.getMessage();
        System.out.println("e: " + cause);
        throw e;
    }
}

From source file:org.openmrs.module.clinicalsummary.io.utils.TaskUtils.java

/**
 * Method to execute a command inside the shell. The command is usually the mysqldump or mysql command.
 *
 * @param commands/*from   ww w.  ja  v  a 2  s. co m*/
 *
 * @throws InterruptedException
 */
public static void executeCommand(final File workingDirectory, final String[] commands) throws Exception {
    Runtime runtime = Runtime.getRuntime();
    Process process;
    if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM)
        process = runtime.exec(commands, null, workingDirectory);
    else
        process = runtime.exec(commands);

    StreamHandler errorHandler = new StreamHandler(process.getErrorStream(), "ERROR");
    StreamHandler outputHandler = new StreamHandler(process.getInputStream(), "OUTPUT");

    ExecutorService executorService = Executors.newCachedThreadPool();

    executorService.execute(errorHandler);
    executorService.execute(outputHandler);

    int exitValue = process.waitFor();
    log.info("Process execution completed with exit value: " + exitValue + " ...");
}

From source file:org.openmrs.module.reportingsummary.api.io.util.InputOutputUtils.java

/**
 * Method to execute a command inside the shell. The command is usually the mysqldump or mysql command.
 *
 * @param commands the command array to be executed
 * @throws Exception when the task execution is interrupted
 *//*  w  ww  .j  av  a  2s. c om*/
public static void executeCommand(final File workingDirectory, final String[] commands) throws Exception {
    Runtime runtime = Runtime.getRuntime();
    Process process;
    if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM)
        process = runtime.exec(commands, null, workingDirectory);
    else
        process = runtime.exec(commands);

    StreamHandler errorHandler = new StreamHandler(process.getErrorStream(), "ERROR");
    StreamHandler outputHandler = new StreamHandler(process.getInputStream(), "OUTPUT");

    ExecutorService executorService = Executors.newCachedThreadPool();

    executorService.execute(errorHandler);
    executorService.execute(outputHandler);

    int exitValue = process.waitFor();
    log.info("Process execution completed with exit value: " + exitValue + " ...");

    executorService.shutdown();
}

From source file:com.dtolabs.rundeck.core.utils.ScriptExecUtil.java

/**
 * Run a command with environment variables in a working dir, and copy the streams
 *
 * @param command      the command array to run
 * @param envMap       the environment variables to pass in
 * @param workingdir   optional working dir location (or null)
 * @param outputStream stream for stdout
 * @param errorStream  stream for stderr
 *
 * @return the exit code of the command//ww  w .j  a  va 2  s. c om
 *
 * @throws IOException          if any IO exception occurs
 * @throws InterruptedException if interrupted while waiting for the command to finish
 */
public static int runLocalCommand(final String[] command, final Map<String, String> envMap,
        final File workingdir, final OutputStream outputStream, final OutputStream errorStream)
        throws IOException, InterruptedException {
    final String[] envarr = createEnvironmentArray(envMap);

    final Runtime runtime = Runtime.getRuntime();
    final Process exec = runtime.exec(command, envarr, workingdir);
    final Streams.StreamCopyThread errthread = Streams.copyStreamThread(exec.getErrorStream(), errorStream);
    final Streams.StreamCopyThread outthread = Streams.copyStreamThread(exec.getInputStream(), outputStream);
    errthread.start();
    outthread.start();
    exec.getOutputStream().close();
    final int result = exec.waitFor();
    errthread.join();
    outthread.join();
    if (null != outthread.getException()) {
        throw outthread.getException();
    }
    if (null != errthread.getException()) {
        throw errthread.getException();
    }
    return result;
}

From source file:org.openmrs.logic.util.LogicUtil.java

/**
 * Generic method to fork a new command for the operating system to run.
 * /*from w  ww  .  j  a  va 2s.  c om*/
 * @param commands the command and the parameters
 * @param workingDirectory the directory where the commands should be invoked
 * @return true when the command executed succesfully.
 */
public static final boolean executeCommand(String[] commands, File workingDirectory) {

    boolean executed = false;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM)
            process = runtime.exec(commands, null, workingDirectory);
        else
            process = runtime.exec(commands);

        ExecutorService executorService = Executors.newCachedThreadPool();

        StreamHandler errorHandler = new StreamHandler(process.getErrorStream(), "ERROR");
        StreamHandler outputHandler = new StreamHandler(process.getInputStream(), "OUTPUT");

        if (executorService == null)
            executorService = Executors.newCachedThreadPool();

        executorService.execute(errorHandler);
        executorService.execute(outputHandler);

        int exitValue = process.waitFor();
        log.info("Process execution completed with exit value: " + exitValue + " ...");

        executed = true;
    } catch (Exception e) {
        log.error("Error generated", e);
    }

    return executed;
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

private static void exec(String[] cmd, String tmpdir) throws IOException, InterruptedException {
    String[] env = new String[] { "PRECOMPILE_STREAMLINE_FILES=1" };

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd, env, new File(tmpdir));

    // any error message?
    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), true);

    // kick them off
    errorGobbler.start();//from  w  ww.j a v a 2s .  c o m

    proc.waitFor();
}

From source file:ExifUtils.ExifReadWrite.java

public static ArrayList<String> exifTool(String[] parameters, File directory) {
    //        final String command[] = "exiftool " + parameters;
    ArrayList<String> lines = new ArrayList<>();
    try {/*from   w  w  w  .j av a 2 s . c o m*/
        Runtime runtime = Runtime.getRuntime();
        Process p = runtime.exec(parameters, null, directory);
        final BufferedReader stdinReader = new BufferedReader(
                new InputStreamReader(p.getInputStream(), "ISO-8859-1"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream(), "ISO-8859-1"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stdinReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stderrReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        int returnVal = p.waitFor();
    } catch (Exception e) {
        errorOut("xmp", e);
    }
    return lines;
}

From source file:org.smartfrog.avalanche.client.sf.compress.ZipUtils.java

public static boolean unTarProc(File tarFile, File outputDir) throws IOException {
    String tarFileName = tarFile.getName();

    if (!tarFile.exists()) {
        log.error("The file " + tarFileName + " does not exist");
        return false;
    }//from w  ww.java  2 s.  co m
    if (!tarFile.isFile()) {
        log.error("The file " + tarFileName + " is not a file");
        return false;
    }
    if (!outputDir.exists()) {
        log.error("The directory " + outputDir + " does not exist");
        return false;
    }
    if (!outputDir.isDirectory()) {
        log.error("The given path " + outputDir + " is not a directory");
        return false;
    }
    if (!outputDir.canWrite()) {
        log.error("Cannot write to the directory " + outputDir);
        return false;
    }

    Runtime run = Runtime.getRuntime();
    String cmd = "tar xf " + tarFile.getAbsolutePath();
    Process p = run.exec(cmd, null, outputDir);
    int exitVal = 0;

    try {
        exitVal = p.waitFor();
    } catch (InterruptedException ie) {
        log.error("Error in un-tarring file " + tarFile.getAbsolutePath());
        return false;
    }
    if (exitVal != 0) {
        log.error("Error in un-tarring file " + tarFile.getAbsolutePath());
        return false;
    } else
        return true;
}