我正在尝试使用 java 捕获外部程序的输出,但我不能。
我有显示它的代码,但没有将它放入变量中。
例如,我将使用 sqlplus 执行我的 oracle 代码“进入 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;
}