Java exec executeCommand(List cmdArray)

Here you can find the source of executeCommand(List cmdArray)

Description

Execute a command and return all the output.

License

Open Source License

Declaration

public static String executeCommand(List<String> cmdArray) throws IOException, InterruptedException 

Method Source Code


//package com.java2s;
/*//ww w .ja v a2 s.  co m
 * This file is part of Fim - File Integrity Manager
 *
 * Copyright (C) 2015  Etienne Vrignaud
 *
 * Fim is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Fim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Fim.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.IOException;
import java.io.InputStream;

import java.util.List;
import java.util.Scanner;

public class Main {
    /**
     * Execute a command and return all the output.
     */
    public static String executeCommand(List<String> cmdArray) throws IOException, InterruptedException {
        ProcessBuilder builder = new ProcessBuilder(cmdArray);
        builder.redirectErrorStream(true);
        Process process = builder.start();

        try (InputStream is = process.getInputStream(); Scanner scanner = new Scanner(is).useDelimiter("$")) {
            String output = scanner.hasNext() ? scanner.next() : "";

            process.waitFor();
            int exitValue = process.exitValue();
            if (exitValue != 0) {
                throw new IllegalArgumentException(
                        String.format("Command execution failed with status: %d\n%s", exitValue, output));
            }

            return output;
        }
    }
}

Related

  1. executeCmdCommand(String command)
  2. executeCmdForReader(String cmd)
  3. executeComand(String[] comand)
  4. executeCommand(final ProcessBuilder pb)
  5. executeCommand(final String cmd)
  6. executeCommand(List command)
  7. executeCommand(String cmd)
  8. executeCommand(String cmd)
  9. executeCommand(String comand)