2

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

3
  • 1
    You use another Thread to read it. Commented Dec 20, 2014 at 7:16
  • I don't think I understand, the problem is that I have no way of getting output from 'assoc' or commands like it. Commented Dec 20, 2014 at 7:22
  • Assuming you refer to Windows, redirect the output of assoc into an output-file and then read the file. support.microsoft.com/kb/323526 When you post a question, please make sure to provide all the necessary details: an example of the content of command, the actual output, the requested output, OS, etc. Commented Dec 20, 2014 at 8:01

1 Answer 1

2

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 ;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.