在JAVA中捕获外部程序的输出

在JAVA中捕获外部程序的输出

本文介绍了在JAVA中捕获外部程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用java来捕获外部程序的输出,但我不能。

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.

我将使用sqlplus执行我的oracle代码into exec.sql
system / orcl @ orcl:user /密码/数据库名称

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;
    }


推荐答案

因为流程将在当你来到你的while循环时,新的线程可能没有输出或不完整的输出。

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.

这篇关于在JAVA中捕获外部程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 10:13