Java Shell Command runCommand(String[] command)

Here you can find the source of runCommand(String[] command)

Description

run Command

License

Open Source License

Declaration

public static String runCommand(String[] command) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    public static String runCommand(String[] command) throws Exception {
        Process process;/*from  www .j  ava2s  . c  om*/
        try {
            process = executeCommand(command);
            process.waitFor();
            String output = toString(process.getInputStream());

            return output;
        } catch (Exception e) {
            throw new Exception(
                    String.format("Failed to execute command %s, %s", getStringFromArray(command), e.getMessage()),
                    e);
        }
    }

    private static Process executeCommand(String[] command) throws Exception {
        return Runtime.getRuntime().exec(command);
    }

    public static String toString(InputStream in) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();

        String read;
        try {
            while ((read = br.readLine()) != null) {
                sb.append(read);
            }
        } catch (IOException e) {
            throw new Exception("Error reading from stream.", e);
        }

        return sb.toString();
    }

    public static String getStringFromArray(String[] command) {
        return Arrays.toString(command).replaceAll("\\[|,|]", "");
    }
}

Related

  1. runCommand(String program, ArrayList args)
  2. runCommand(String s)
  3. runCommand(String[] args)
  4. runCommand(String[] args)
  5. runCommand(String[] cmdArray, String extraPath, String libPath)
  6. runCommand(String[] command)
  7. runCommandAndWait(String command, String workingDir, String extraPath)
  8. runCommandArray(String[] command)
  9. runCommandGetOutput(String startFolder, String[] args, int[] cmdReturnValue)