1

I'm using the following object, to run a bash command through my Java code.

public class Scripter {
    private final String[] ENV = {"PATH=/bin:/usr/bin/"};

    private String cmd;
    private Process process;

    public Scripter(String cmd) throws IOException {
        this.cmd = cmd;
        process = Runtime.getRuntime().exec(cmd, ENV);
    }
}

Now I'm calling this object and trying to print the output in this function.

public static void main(String[] args) {
    Scripter gitCheck;

    try {
        gitCheck = new Scripter("git --version");
    } catch (IOException e) {
        e.printStackTrace();
    }
    Scanner sc = new Scanner(System.in);
    if (sc.hasNext()) {
        System.out.println(sc.next());
    }
}

The program goes on an infinite loop and does nothing. What am I doing wrong here?

3
  • There's no loop in your code. Commented Jul 1, 2016 at 20:37
  • What do you pipe into the standard input of this program? (Not the git command, the Java program) You are reading from that; if you don't pipe anything in (and close it), it'll just block indefinitely (it's not an infinite loop). Commented Jul 1, 2016 at 20:38
  • 1
    It's not in an infinite loop, it's waiting for you to type something at sc.next(). You need to read about ProcessBuilder and how to retrieve the input and output streams of the process. System.in does not magically get attached to the process. Commented Jul 1, 2016 at 20:39

1 Answer 1

3

You're trying to read a string from the standard input of the Java process:

Scanner sc = new Scanner(System.in);
if (sc.hasNext()) { ... }

So your Java program will block until you actually pass something into its standard input, or close the standard input.

(It's not an infinite loop, and it has nothing to do with the git command)

If you're trying to read the output of the git command, you'll need to read process.getInputStream() instead of System.in.

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

1 Comment

This worked for me. I modified my code to do this. InputStream is = gitCheck.getProcess().getInputStream(); System.out.println(convertStreamToString(is));

Your Answer

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