Reputation:
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?
Upvotes: 1
Views: 111
Reputation: 140299
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
.
Upvotes: 3