我正在创建一个程序,它将通过调用java程序的pl / sql函数通过命令行运行某些程序。我目前遇到的问题是当我用一个我知道不存在的文件测试程序时输入流返回一个空值并且它没有得到错误流。我不认为我可以使用ProcessBuilder来合并错误和输入,因为如果有错误,我会将值返回到pl / sql中的函数以停止并将错误代码复制到数据库中。
import java.io.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class runScriptNew {
private static boolean error = false;
public static String run(String command)
{
ExecutorService threadExecutor;
String retVal = null;
try
{
String cmd = command;
System.out.println("Starting the command..");
Process p = Runtime.getRuntime().exec("cmd /C " + cmd);
threadExecutor = Executors.newCachedThreadPool();
threadExecutor.execute(new StreamGobbler(p.getInputStream()));
threadExecutor.execute(new StreamGobbler(p.getErrorStream(), true));
p.waitFor(); // Wait for proc to complete.
threadExecutor.shutdown();
if(error == true)
{
retVal = "ERROR";
}
else
{
retVal = "OK";
}
System.out.println(error);
}
catch(Exception e)
{
e.printStackTrace();
retVal = e.toString();
}
return retVal;
}
public static class StreamGobbler implements Runnable
{
private InputStream input;
private Boolean errorToken = false;
public StreamGobbler(InputStream inStream)
{
input = inStream;
}
public StreamGobbler(InputStream inStream, Boolean bool)
{
input = inStream;
errorToken = bool;
}
public void run() {
StringBuffer line = new StringBuffer();
BufferedReader buffRead = null;
try
{
buffRead = new BufferedReader(new InputStreamReader(input));
while (buffRead.readLine() != null)
{
line.append(buffRead.readLine());
line.append("\n");
if (errorToken == true)
{
error = true;
}
}
System.out.println(line.toString());
buffRead.close();
}
catch( IOException e)
{
e.printStackTrace();
error = true;
}
finally
{
try {
buffRead.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
任何帮助都将不胜感激。
import java.io.*;
public class runScript {
public static String run(String args) throws IOException{
String retVal = null;
int errorNum;
try
{
String cmd = args;
System.out.println("Starting the command..");
Process p = Runtime.getRuntime().exec("cmd /C " + cmd);
errorNum = p.waitFor(); // Wait for proc to complete.
//if errorNum does not equal 0 then there was an error while handling the
//command
if(errorNum != 0)
{
retVal = "ERROR";
}
else
{
retVal = "OK";
}
}
catch(Exception e)
{
e.printStackTrace();
retVal = e.toString();
}
return retVal;
}
}
检查waitFor()调用修复了该问题。结果我不需要处理输入和错误流。
答案 0 :(得分:0)
好的,这里有很多事,但我会尽我所能来帮助你。
首先,系统命令cmd /c <command>
执行<command>
然后终止。这意味着启动一个单独的进程,而不会将其流重定向到任何位置。有没有理由不能直接执行<command>
?
其次,我不认为(我不确定,但我不认为)Runtime.exec(String)
像你认为的那样执行完整的字符串。我相信Runtime.exec(String)
用于执行没有参数的系统命令。您应该使用Runtime.exec(String[])
来传递参数。例如
Runtime.getRuntime().exec(new String[] {"cmd", "/c", command});
更新:我错了,便捷方法Runtime.exec(String)已经使用了一个标记生成器来拆分命令。但是,这可能不是你想要的。
最后,你的行
while (buffRead.readLine() != null)
不正确。这将读取一行输入,将其与null对齐并将其放在地板上。你想要更像
的东西String line = null;
while ((line = buffRead.readLine()) != null)
如果您需要流重定向,那么您真的应该使用ProcessBuilder
来启动新进程。