gstackoverflow
gstackoverflow

Reputation: 36996

How to get result of console command from java code?

I have following code:

ProcessBuilder pb = new ProcessBuilder("dir"); // or cat in linux
Process p = pb.start();
p.waitFor();
String result = IOUtils.toString(p.getInputStream(), "UTF-8");
System.out.println(result);

It throws

java.io.IOException: Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) ~[na:1.8.0_111]

I understand that I can write something like this:

ProcessBuilder pb = new ProcessBuilder("test.bat");

and inside test.bat you can write

dir

But it returns:

D:\nsd-rest>dir
 Volume in drive D is SECOND
 Volume Serial Number is CE52-8896

 Directory of D:\nsd-rest

03/24/17  15:53    <DIR>          .
03/24/17  15:53    <DIR>          ..
03/24/17  12:00               249 .gitignore
03/24/17  16:54    <DIR>          .idea
03/24/17  15:01    <DIR>          .mvn
03/24/17  12:00             7,058 mvnw
03/24/17  12:00             5,006 mvnw.cmd
03/24/17  15:53             6,265 nsd-rest.iml
03/24/17  15:52             1,993 pom.xml
03/24/17  15:01    <DIR>          src
03/24/17  15:19    <DIR>          target
03/24/17  16:52                 3 test.bat
               6 File(s)         20,574 bytes
               6 Dir(s)  587,412,844,544 bytes free

Row

D:\nsd-rest>dir

is redundant.

When I invoke bat file I feel that I do something incorrect.

Can you provide correct solution?

P.S. instead of dir can be any executable file.

Upvotes: 0

Views: 422

Answers (1)

Dmitry Zvorygin
Dmitry Zvorygin

Reputation: 477

There's no dir executable actually - e.g. you can't find dir.exe anywhere on windows. This is pseudo-command which exist in cmd.exe executable context only.

If you want to get "dir" output - you can simply run cmd.exe /c dir

Also there's bug in your program:

p.waitFor();
String result = IOUtils.toString(p.getInputStream(), "UTF-8");

If program output is large enough and wouldn't fit into output buffer, p.waitFor() would never end - because buffer is overflown and nobody is reading it. I'd suggest swap these lines(or even better - read couple articles about interprocess IO, that's related to everything not to java world only).

Upvotes: 1

Related Questions