gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:33:38 25 4
gpt4 key购买 nike

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

我有显示它的代码,但没有将它放入变量中。

例如,我将使用 sqlplus 来执行我的 oracle 代码“into exec.sql”system/orcl@orcl : 用户名/密码/数据库名

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 循环时,很可能没有输出或输出不完整。

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

因此您需要等待该过程完成,然后再尝试与其输出进行交互。尝试使用 Process.waitFor()暂停当前​​线程的方法,直到您的进程有机会完成。

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

这只是一种简单的方法,您还可以在进程并行运行时处理其输出,但随后您需要监视进程的状态,即它是否仍在运行或已完成,以及输出的可用性.

关于java - 在JAVA中捕获外部程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14542448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com