Reputation: 1867
I have written this code which should execute a command on shell to search pattern ">" in a text file , when I try same command on shell it works fine but when I try execute same command using java , it doesn't work for me as buffered reader returns null.Can somebody tell that what I have done wrong in this.
Code:
String filename="/home/abhijeet/sample.txt";
Process contigcount_p;
String command_to_count="grep \">\" "+filename+" | wc -l";
System.out.println("command for counting contigs "+command_to_count);
contigcount_p=Runtime.getRuntime().exec(command_to_count);
contigcount_p.wait();
BufferedReader reader =
new BufferedReader(new InputStreamReader(contigcount_p.getInputStream()));
System.out.println("chkk buffer"+reader.readLine());
Upvotes: 0
Views: 218
Reputation: 531
Think you have to read inputStream in loop before waiting and use waitFor() rather than wait() to wait for the process to finish if needed, although thats not necassary in this case it will have finished when the reading loop completes.
e.g:
....
contigcount_p=Runtime.getRuntime().exec(command_to_count);
BufferedReader reader = new BufferedReader(new InputStreamReader(contigcount_p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("chkk buffer"+line);
}
reader.close()
contigcount_p.waitFor();
Upvotes: 0
Reputation: 1867
According to comments i have resolved thsi issue by wrapping commands in a shell by using
Runtime.getRuntime().exec(new String[]{"sh", "-c", "grep \">\" "+filename+" | wc -l"});
By this command was executing successfully but i was still not able to get its output by bufferedreader , as still output value was NULL, so what i have done is that i in first command i have redicted it's output to a temporary file
Runtime.getRuntime().exec(new String[]{"sh", "-c", "grep \">\" "+filename+" | wc -l > temp"});
and I have created one more process to execute a read on this command and then to remove that temporary file.
Please refer to :- shell Command execution Failing when executed from Java
Note: I know that this is not a perfect solution for this as output should be directly available by bufferedreader, but could'd find any solution yet, Any answer is still welcom, for temporary purpose i have used this answer will remove and accept answer if someone gives a solution for this.
Upvotes: 1