Java Runtime.getRuntime(): getting output from executing a command line program

前端 未结 12 1380
清歌不尽
清歌不尽 2020-11-22 00:18

I\'m using the runtime to run command prompt commands from my Java program. However, I\'m not aware of how I can get the output the command returns.

Here is my code:

相关标签:
12条回答
  • 2020-11-22 00:49

    Also we can use streams for obtain command output:

    public static void main(String[] args) throws IOException {
    
            Runtime runtime = Runtime.getRuntime();
            String[] commands  = {"free", "-h"};
            Process process = runtime.exec(commands);
    
            BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            lineReader.lines().forEach(System.out::println);
    
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            errorReader.lines().forEach(System.out::println);
        }
    
    0 讨论(0)
  • 2020-11-22 00:50

    @Senthil and @Arend answer (https://stackoverflow.com/a/5711150/2268559) mentioned ProcessBuilder. Here is the example using ProcessBuilder with specifying environment variables and working folder for the command:

        ProcessBuilder pb = new ProcessBuilder("ls", "-a", "-l");
    
        Map<String, String> env = pb.environment();
        // If you want clean environment, call env.clear() first
        //env.clear();
        env.put("VAR1", "myValue");
        env.remove("OTHERVAR");
        env.put("VAR2", env.get("VAR1") + "suffix");
    
        File workingFolder = new File("/home/user");
        pb.directory(workingFolder);
    
        Process proc = pb.start();
    
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    
        // Read the output from the command:
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null)
            System.out.println(s);
    
        // Read any errors from the attempted command:
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null)
            System.out.println(s);
    
    0 讨论(0)
  • 2020-11-22 00:53

    If use are already have Apache commons-io available on the classpath, you may use:

    Process p = new ProcessBuilder("cat", "/etc/something").start();
    String stderr = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
    String stdout = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
    
    0 讨论(0)
  • 2020-11-22 00:55

    A quicker way is this:

    public static String execCmd(String cmd) throws java.io.IOException {
        java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    

    Which is basically a condensed version of this:

    public static String execCmd(String cmd) throws java.io.IOException {
        Process proc = Runtime.getRuntime().exec(cmd);
        java.io.InputStream is = proc.getInputStream();
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        String val = "";
        if (s.hasNext()) {
            val = s.next();
        }
        else {
            val = "";
        }
        return val;
    }
    

    I know this question is old but I am posting this answer because I think this may be quicker.

    Edit (For Java 7 and above)

    Need to close Streams and Scanners. Using AutoCloseable for neat code:

    public static String execCmd(String cmd) {
        String result = null;
        try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
                Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
            result = s.hasNext() ? s.next() : null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 00:56

    Here is the way to go:

    Runtime rt = Runtime.getRuntime();
    String[] commands = {"system.exe", "-get t"};
    Process proc = rt.exec(commands);
    
    BufferedReader stdInput = new BufferedReader(new 
         InputStreamReader(proc.getInputStream()));
    
    BufferedReader stdError = new BufferedReader(new 
         InputStreamReader(proc.getErrorStream()));
    
    // Read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
    
    // Read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
    

    Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

    0 讨论(0)
  • 2020-11-22 01:01

    Adapted from the previous answer:

    public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
        RLog.i(TAG, "Running command:", cmd);
    
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd);
    
        //String[] commands = {"system.exe", "-get t"};
    
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    
        StringBuffer stdOut = new StringBuffer();
        StringBuffer errOut = new StringBuffer();
    
        // Read the output from the command:
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
            stdOut.append(s);
        }
    
        // Read any errors from the attempted command:
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
            errOut.append(s);
        }
    
        if (callback == null) {
            return stdInput.toString();
        }
    
        int exitVal = proc.waitFor();
        callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);
    
        return stdInput.toString();
    }
    
    public interface CmdExecResult{
        void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
    }
    
    0 讨论(0)
提交回复
热议问题