Java Shell Command runShell(File workspace, String... shellElements)

Here you can find the source of runShell(File workspace, String... shellElements)

Description

run Shell

License

Apache License

Declaration

public static String runShell(File workspace, String... shellElements) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {
    public static String runShell(File workspace, String... shellElements) throws Exception {
        ProcessBuilder pb;//from  w ww.j  a  va 2s .  c om
        Process process;

        StringBuilder result = new StringBuilder();
        InputStream in = null;
        InputStreamReader inReader = null;
        BufferedReader bufferReader = null;

        StringBuilder errorMsg = new StringBuilder();
        InputStream error = null;
        InputStreamReader errorReader = null;
        BufferedReader errorBufferReader = null;

        try {
            pb = new ProcessBuilder(shellElements).directory(workspace);
            process = pb.start();

            in = process.getInputStream();
            inReader = new InputStreamReader(in, "UTF-8");
            bufferReader = new BufferedReader(inReader);
            String line = null;

            error = process.getErrorStream();
            errorReader = new InputStreamReader(error);
            errorBufferReader = new BufferedReader(errorReader);
            String errorLine = null;

            while ((line = bufferReader.readLine()) != null || (errorLine = errorBufferReader.readLine()) != null) {
                if (line != null)
                    result.append(line);
                if (errorLine != null)
                    errorMsg.append(errorLine);
            }
            process.waitFor();

            if (!errorMsg.toString().isEmpty())
                throw new RuntimeException(errorMsg.toString());
            return result.toString();
        } finally {
            if (bufferReader != null)
                bufferReader.close();
            if (inReader != null)
                inReader.close();
            if (in != null)
                in.close();
        }
    }
}

Related

  1. runCommandAndWait(String command, String workingDir, String extraPath)
  2. runCommandArray(String[] command)
  3. runCommandGetOutput(String startFolder, String[] args, int[] cmdReturnValue)
  4. runCommandPrompt(final String commandLine, final IPath path)
  5. runCommandWithOutput(String cmd)
  6. runShell(String cmd)
  7. runShell(String shStr)
  8. runShellCommand(String command)
  9. runShellCommand(String command)