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.
waitFor()returns after the process has finished. Call it after you are done reading from the InputStream.