Reputation: 81
Using ProcessBuilder in JAVA I am able to run simple terminal commands like ls,pwd,echo etc..etc... But following code is getting terminated , don't know why??
public static void main(String[] args) throws Exception
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("echo 'T W O N E I G H T' | /home/saj/g2p/mosesdecoder-master/bin/moses -f /home/saj/g2p/working/binarised-model/moses.ini");
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null)
{
System.out.println(line);
}
}
This command works perfectly from terminal and takes around 15 seconds to run and gives output. I have gone through similar topics on stackoverflow but did not found any help. Please help in this regard. Thanks in advance.
Upvotes: 0
Views: 688
Reputation: 136
Refer this code this may help u....use bash.Just replace your command with echo command
ProcessBuilder b = new ProcessBuilder("bash","-c","echo abc");
Process termProc = null;
try {
termProc = b.start();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(termProc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(termProc.getErrorStream()));
String s = null;
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
while ((s = stdError.readLine()) != null)
{
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 2
Reputation: 6783
Consider monitoring both the InputStream and ErrorStream. Chances are that the output is probably getting written to the ErrorStream and that's why you don't see anything getting displayed.
Here's a good example from Javaworld regarding some of the common pitfalls of Runtime.exec() and how to go about using it.
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
Consider an update to your code along these lines:
public static void main(String[] args) throws Exception
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("echo 'T W O N E I G H T' | /home/saj/g2p/mosesdecoder-master/bin/moses -f /home/saj/g2p/working/binarised-model/moses.ini");
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null)
{
System.out.println(line);
}
BufferedReader b = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = "";
while ((line = b.readLine()) != null)
{
System.out.println(line);
}
p.waitFor();
}
Note: I would suggest creating threads to handle displaying your output from inputstream and errorstream as in the example link that I posted above.
Upvotes: 0