Here you can find the source of runCommandGetOutput(String startFolder, String[] args, int[] cmdReturnValue)
Parameter | Description |
---|---|
startFolder | Initial working directory, or null for user's home-dir. |
args | array of tokens to pass, where args[0] is name of program to run. |
cmdReturnValue | - int[0] is return value of process |
public static List<String> runCommandGetOutput(String startFolder, String[] args, int[] cmdReturnValue) throws IOException, InterruptedException
//package com.java2s; /*** Java Commons and Niceties Library from CrunchyNoodles.com *** Copyright (C) 2014 in USA by Brian Witt , bwitt@value.net ***/* www .java 2 s .c om*/ *** Licensed under the Apache License, Version 2.0 ( the "License" ) ; *** you may not use this file except in compliance with the License. *** You may obtain a copy of the License at: *** http://www.apache.org/licenses/LICENSE-2.0 *** *** Unless required by applicable law or agreed to in writing, software *** distributed under the License is distributed on an "AS IS" BASIS, *** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *** See the License for the specific languatge governing permissions and *** limitations under the License. ***/ import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { /*** * Execute process and collect all output. * If exec failure, then returns {@code cmdReturnValue[0]} as -1 and {@code null} * instead of string-array. * * @param startFolder Initial working directory, or null for user's home-dir. * @param args array of tokens to pass, where {@code args[0]} is name of program to run. * @param cmdReturnValue - int[0] is return value of process * @return captured output as string-list on successful exec, else null if troubles. * * @see http://stackoverflow.com/questions/1410741/want-to-invoke-a-linux-shell-command-from-java */ public static List<String> runCommandGetOutput(String startFolder, String[] args, int[] cmdReturnValue) throws IOException, InterruptedException { List<String> commands = new ArrayList<String>(); commands.addAll(Arrays.asList(args)); cmdReturnValue[0] = -1; if (startFolder == null) { startFolder = System.getProperty("user.home"); } // Run program, gathering all its output. Combines STDOUT and STDERR together. ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File(startFolder)); pb.redirectErrorStream(true); Process process = pb.start(); List<String> out = new ArrayList<String>(2000); // Use the input stream connected to the normal and error output of the subprocess. BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; //Read output while ((line = br.readLine()) != null) { out.add(line); } cmdReturnValue[0] = process.waitFor(); return out; } }