Java exec executeShellCommand(String command, File dir)

Here you can find the source of executeShellCommand(String command, File dir)

Description

Run a shell command in the specified directory.

License

Open Source License

Parameter

Parameter Description
command command to be run
dir the directory to run the command in. If dir is null, runs it in the current directory of the process.

Return

output of the command

Declaration

public static String executeShellCommand(String command, File dir) 

Method Source Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.File;

import java.io.InputStreamReader;

public class Main {
    /**/*from   w w w  . j  a va 2  s  .  c o  m*/
     * Run a shell command in the specified directory.  
     * @param command command to be run
     * @param dir the directory to run the command in. If dir is null, runs it in the current directory of the process.
     * @return output of the command
     */
    public static String executeShellCommand(String command, File dir) {

        StringBuffer output = new StringBuffer();
        System.out.println("Shell command:" + command);

        Process p;
        try {
            p = Runtime.getRuntime().exec(command, null, dir);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();

    }
}

Related

  1. executePUT(DataInputStream sockInp, DataOutputStream sockOutp)
  2. executeServer()
  3. executeShellCmdAndReturn(String cmd)
  4. executeShellCommand(String command)
  5. executeShellCommand(String command)
  6. executeShellCommand(String commandName)
  7. executeShellScript(final String shellScript, final File tempDirectory)
  8. executeSMTPSend(String fromEmailAddress, List toEmailAddresses, String subject, String body, Transport transport, File... fileAttachments)
  9. execVmCmdAsync(String vmNameSpace, String vmKey, String vmUser, String vmIp, String vmCmd, String controllerOutPutFile)