Execution in Java code of an external program that takes arguments

Process p; String line; String path; String[] params = new String [3]; params[0] = "D:\\prog.exe"; params[1] = picA+".jpg"; params[2] = picB+".jpg"; try { p = Runtime.getRuntime().exec(params); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) System.out.println(line); input.close(); } catch (IOException e) { System.out.println(" procccess not read"+e); } 

I get no mistake, just nothing. In cmd.exe, prog.exe is working fine.

What to improve to make this code work?

+3
source share
4 answers

Perhaps you should use waitFor () to get the result code. This means that the dump of the standard output must be executed in another thread:

 String path; String[] params = new String [3]; params[0] = "D:\\prog.exe"; params[1] = picA+".jpg"; params[2] = picB+".jpg"; try { final Process p = Runtime.getRuntime().exec(params); Thread thread = new Thread() { public void run() { String line; BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) System.out.println(line); input.close(); } catch (IOException e) {System.out.println(" procccess not read"+e);} }; thread.start(); int result = p.waitFor(); thread.join(); if (result != 0) { System.out.println("Process failed with status: " + result); } 
+2
source

Use p = new ProcessBuilder(params).start(); instead

p = Runtime.getRuntime().exec(params);

In addition, it looks normal.

+3
source

I just tried this on my system:

 public static void main(String[] args) throws IOException { String[] params = { "svn", "help" }; Process p = Runtime.getRuntime().exec(params); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } input.close(); } 

and it worked fine. Are you sure that the program you are using actually prints something to the console? I see that jpegs is required as input, maybe it writes a file, not stdout.

+1
source

Just like reading from a process input stream, you can also read from an error stream as follows:

  Process p; String line; String path; String[] params = new String [3]; params[0] = "D:\\prog.exe"; params[1] = picA+".jpg"; params[2] = picB+".jpg"; try { p = Runtime.getRuntime().exec(params); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); BufferedReader error = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = input.readLine()) != null) System.out.println(line); while ((line = error.readLine()) != null) System.out.println(line); input.close(); error.close(); } catch (IOException e) { System.out.println(" procccess not read"+e); } 
0
source

Source: https://habr.com/ru/post/913417/


All Articles