Reputation: 3
I am running the following code, and it stops at waitfor()
function. What could be the reason and how can I solve it?
String line;
Process albumProcess;
try {
albumProcess = Runtime.getRuntime().exec(
"iconv -f UTF-16 -t UTF-8 /home/gozenem/"+ xmlFileName +
".xml | grep albumID");
albumProcess.waitFor();
BufferedReader in = new BufferedReader(
new InputStreamReader(albumProcess.getInputStream()));
ArrayList<String> lineList = new ArrayList<String>();
while ((line = in.readLine()) != null) {
lineList.add(line);
}
result[0] = lineList.size();
albumProcess.destroy();
} catch (Exception e) {}
Upvotes: 0
Views: 1917
Reputation: 120576
The | grep ...
is not consuming the output from the command as you expect because getRuntime().exec
does not understand piping symbols. The process gets bogged down waiting for something to consume its output and its getting passed bogus command line arguments "|"
, "grep"
, and "albumId"
.
A shell will understand |
but execv
will not, so you need to use bash -c
instead to get a shell to do the piping (see java shell for executing/coordinating processes? do the piping yourself (see Pipe between java processes on command shell not reliable working). Java 7 has a new ProcessBuilder
class that makes it easy to set up pipes so you can use those if you're only running on a bleeding edge JVM.
Once you've got grep
running, if there's a bunch of lines that match, it may still fill up the buffer, so you need something sitting on the buffer consuming the process's output stream. Moving
albumProcess.waitFor();
after the while
loop should do it.
Upvotes: 2
Reputation: 326
I think you should try to read the output from the process before waiting on it. Otherwise, if the command outputs to much then the buffer may get filled.
Have a look at this article which explains how to read from the process: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
Upvotes: 1