java - Can't get output from Runtime.exec() -
i have written code execute command on shell through java:
string filename="/home/abhijeet/sample.txt"; process contigcount_p; string command_to_count="grep \">\" "+filename+" | wc -l"; system.out.println("command counting contigs "+command_to_count); contigcount_p=runtime.getruntime().exec(command_to_count); contigcount_p.wait();
as pipe symbols being used not able execute command successfully.as per last question's discussion have wrapped variables in shell:
runtime.getruntime().exec(new string[]{"sh", "-c", "grep \">\" "+filename+" | wc -l"});
which worked me executes command on shell , still when try read output using buffered reader :
bufferedreader reader = new bufferedreader(new inputstreamreader(contigcount_p.getinputstream())); string line=" "; while((line=reader.readline())!=null) { output.append(line+"\n"); }
it returns null value ,i have found temporary solution have discussed on previous question: link, use right way of doing reading it's output using bufferedreader.
when used command line of {"sh", "-c", "grep \">\" "+filename+" | wc -l"}
kept overriding file
i had change quotes double quoted, {"sh", "-c", "grep \"\">\"\" "+filename+" | wc -l"}
so, using contents of test file...
> > > not new line >
and using code...
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; public class testprocess { public static void main(string[] args) { string filename = "test.tx"; string test = "grep \"\">\"\" "+filename+" | wc -l"; system.out.println(test); try { processbuilder pb = new processbuilder("sh", "-c", test); pb.redirecterror(); process p = pb.start(); new thread(new consumer(p.getinputstream())).start(); int ec = p.waitfor(); system.out.println("ec: " + ec); } catch (ioexception | interruptedexception exp) { exp.printstacktrace(); } } public static class consumer implements runnable { private inputstream is; public consumer(inputstream is) { this.is = is; } @override public void run() { try (bufferedreader reader = new bufferedreader(new inputstreamreader(is))){ string value = null; while ((value = reader.readline()) != null) { system.out.println(value); } } catch (ioexception exp) { exp.printstacktrace(); } } } }
i able produce output...
grep "">"" test.tx | wc -l 4 ec: 0
generally, when dealing external processes, it's easier use processbuilder
, has nice options, including redirecting error/stdout , setting execution context directory...
Comments
Post a Comment