Capturing the output of an external program in JAVA

I am trying to capture the output of an external program using java, but I cannot.

I have code to show it but not put it in a variable.

I will use, for example, sqlplus to execute my oracle code "in exec.sql" system / orcl @orcl: username / password / database name

public static String test_script () { String RESULT=""; String fileName = "@src\\exec.sql"; String sqlPath = "."; String arg1="system/orcl@orcl"; String sqlCmd = "sqlplus"; String arg2 = fileName; try { String line; ProcessBuilder pb = new ProcessBuilder(sqlCmd, arg1, arg2); Map<String, String> env = pb.environment(); env.put("VAR1", arg1); env.put("VAR2", arg2); pb.directory(new File(sqlPath)); pb.redirectErrorStream(true); Process p = pb.start(); BufferedReader bri = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = bri.readLine()) != null) { RESULT+=line; } System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } return RESULT; } 
+8
java output exec
source share
2 answers

Since the process will run in a new thread, there is probably no way out or incomplete output available when you go to your while loop.

 Process p = pb.start(); // process runs in another thread parallel to this one BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); // bri may be empty or incomplete. while ((line = bri.readLine()) != null) { RESULT+=line; } 

Therefore, you need to wait for the process to complete before trying to interact with it. Try using the Process.waitFor () method to pause the current thread until your process can complete.

 Process p = pb.start(); p.waitFor(); // wait for process to finish then continue. BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = bri.readLine()) != null) { RESULT+=line; } 

This is a simple approach that you can also process the output of a process during its parallel operation, but then you will need to control the state of the process, that is, it is still running or completed, and the availability of output.

+6
source share

Use Apache Commons Exec , it will make your life much easier. Check out the tutorials for basic usage information. To read the command line output after receiving the executor object (possibly DefaultExecutor ), create an OutputStream for any stream you want (for example, an instance of FileOutputStream may be, or System.out ) and:

 executor.setStreamHandler(new PumpStreamHandler(yourOutputStream)); 
+6
source share

All Articles