Java exec executeShellCommand(String commandName)

Here you can find the source of executeShellCommand(String commandName)

Description

This method executes a shell command from Java

License

Open Source License

Parameter

Parameter Description
commandName String the requested command name with args

Return

String the output of the command processing

Declaration

public static String executeShellCommand(String commandName) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Main {
    /**/* w w w . ja  v  a 2  s  .  co  m*/
     * This method executes a shell command from Java
     *
     * @param commandName String the requested command name with args
     * @return String the output of the command processing
     */
    public static String executeShellCommand(String commandName) {
        String result = "";

        // Put the english locale for the list command
        Map<String, String> environment = new HashMap<String, String>(System.getenv());
        environment.put("LC_ALL", "en_EN");
        String[] envp = new String[environment.size()];
        int count = 0;
        for (Map.Entry<String, String> entry : environment.entrySet()) {
            envp[count++] = entry.getKey() + "=" + entry.getValue();
        }

        try {
            Process p = Runtime.getRuntime().exec(commandName, envp);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

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

            return result;
        } catch (Exception e) {
            return result;
        }
    }
}

Related

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