9

I'm trying to capture output of an external program using java but I can't.

I have the code to show it, but not to put it into a variable.

I will use, for example, sqlplus to execute my oracle code "into exec.sql" system/orcl@orcl : user/password/DB 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;
    }
7
  • 1
    What you are asking is not clear. You can see it with System.out.println(line);, but RESULT is empty? Commented Jan 26, 2013 at 23:00
  • RESULT is empty at the beginning but in the while loop I made ​​the concatenation --> RESULT+=line; Commented Jan 26, 2013 at 23:06
  • ok but can you see the lines printed with System.out.println(line);? Also note that because you have redirected the error stream, you don't need bre - everything will be streamed to bri. Commented Jan 26, 2013 at 23:07
  • 1
    Shouldn´t you read from the outputstream of the external program? p.getOutputStream() Commented Jan 26, 2013 at 23:12
  • I corrected the mistakes Commented Jan 26, 2013 at 23:17

2 Answers 2

10

Because the Process will execute in a new thread it's likely that there is no output or incomplete output available when you come 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;
}

So you need to wait for the process to complete before attempting to interact with it's output. Try using the Process.waitFor() method to pause the current thread until your process has had an opportunity to 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 only a simple approach you could also process the output of the process while it runs in parallel but then you would need to monitor the status of the process i.e. is it still running or has it completed, and the availability of output.

Sign up to request clarification or add additional context in comments.

Comments

7

Use Apache Commons Exec, it will make your life much easier. Check the tutorials for information about basic usage. To read the command line output after obtaining an executor object (probably DefaultExecutor), create an OutputStream to whatever stream you wish (i.e a FileOutputStream instance may be, or System.out), and:

executor.setStreamHandler(new PumpStreamHandler(yourOutputStream));

5 Comments

It's a java library. Trust me, it will save you a LOT of effort. If you face ANY trouble with, post it right here and I will be glad to help you, anytime :)
10xxxxxxxxxxxxxxxxxxxx I'm gonna test it now :D
@AHmédNet, that's great to know brother :) It will save you a lot of trouble inshaa Allah
I'm confused - does it write both stdout and stderr to the same pump stream handler?
ah yes, has multiple args.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.