1

I'm trying to write a Java program to run terminal command. Googling and SO got me to here:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Detector {
    public static void main(String[] args) {

        String[] cmd = {"ls", "-la"};
        try {
            Process p = Runtime.getRuntime().exec(cmd);

            BufferedReader reader = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine()) !=null){
                System.out.println(line);
            }
            p.waitFor();

        } catch (IOException  | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

So far, so good. The problem is if I try to run a command like "python -V" via

String[] cmd = {"python", "-V"};

The program will run, but no output is actually printed out. Any ideas?

1
  • python -V by default writes to STDERR, not STDOUT. Changing it to python -V 2>&1 should work, but I am sure there is someway to do this in Java without the 2>&1 part Commented Mar 14, 2016 at 22:20

1 Answer 1

1

The output you see on your command line when running python -V is actually being printed to standard error. To capture this, you need to use a different InputStream, such as this:

BufferedReader errorReader = new BufferedReader(
    new InputStreamReader(p.getErrorStream()));

The rest of your code is fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, that did the trick! Thanks very much. Strange how it does that.

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.