Here you can find the source of runSimpleCommand(String command, String directory)
Parameter | Description |
---|---|
command | The command to run |
directory | The working directory to run the command in |
Parameter | Description |
---|---|
IOException | If the command failed |
InterruptedException | If the command was halted |
public static String runSimpleCommand(String command, String directory) throws IOException, InterruptedException
/*//w w w. j a va2s.c om Copyright (c) Inexas 2010 Modifications licensed under the Inexas Software License V1.0. You may not use this file except in compliance with the License. The License is available at: http://www.inexas.com/ISL-V1.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 language governing permissions and limitations under the License. The original file and contents are licensed under a separate license: see below. */ import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import org.apache.log4j.Logger; public class Main{ private static final Logger log = Logger.getLogger(FileUtil.class); /** * Runs a simple command in given directory. The environment is inherited * from the parent process (e.g. the one in which this Java VM runs). * * @return Standard output from the command. * @param command * The command to run * @param directory * The working directory to run the command in * @throws IOException * If the command failed * @throws InterruptedException * If the command was halted */ public static String runSimpleCommand(String command, String directory) throws IOException, InterruptedException { StringBuffer result = new StringBuffer(); log.info("Running simple command " + command + " in " + directory); Process process = Runtime.getRuntime().exec(command, null, new File(directory)); BufferedReader stdout = null; BufferedReader stderr = null; try { stdout = new BufferedReader(new InputStreamReader( process.getInputStream())); stderr = new BufferedReader(new InputStreamReader( process.getErrorStream())); String line; while ((line = stdout.readLine()) != null) { result.append(line + "\n"); } StringBuffer error = new StringBuffer(); while ((line = stderr.readLine()) != null) { error.append(line + "\n"); } if (error.length() > 0) { log.error("Command failed, error stream is: " + error); } process.waitFor(); } finally { // we must close all by exec(..) opened streams: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 process.getInputStream().close(); if (stdout != null) stdout.close(); if (stderr != null) stderr.close(); } return result.toString(); } }