Java Command Line Output

16,358

I don't have a windows machine to test this on, but generally to get the output for those builtins you run cmd.exe as the program and pass it the command as an argument.

Now, this has some limitations, because when the command finishes the executable stops. So if you do a cd command, it will work, but it only affect the subprocess, not your process. For those sorts of things, if you want them to change the state of your process, you'll need to use other facilities.

This version works on a Mac:

import java.io.*;
public class cmd {
    public static void  
        main(String[] argv){
        String line;
        String[] cmd = {"bash","-c","ls"};
        System.out.println("Hello, world!\n");
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader input =
                new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            input.close();
        } catch (Exception e) {
        }
        return ;
    }
}
Share:
16,358
lsnow2017
Author by

lsnow2017

Updated on June 04, 2022

Comments

  • lsnow2017
    lsnow2017 almost 2 years

    I am using the following code to execute a command in java and getting the output:

    String line;
            try {
                System.out.println(command);
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = input.readLine()) != null) {
                    print(line);
                }
                input.close();
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
    

    However, apparently the command 'tree' and 'assoc' and others aren't actually their own programs that can be run through Java, rather they are coded in as parts of command prompt, so I cannot get the output. Is there actually any way to do this? Thank you