2011-05-03 92 views
0

我使用process = Runtime.getRuntime().exec(cmd,null,new File(path)); 以执行文件中的一些SQL(abz.sql)问题与运行调用Runtime.getRuntime(时)EXEC

命令是:

"sqlplus "+ context.getDatabaseUser()  + "/" 
      + context.getDatabasePassword() + "@" 
      + context.getDatabaseHost()  + ":" 
      + context.getDatabasePort()  + "/" 
      + context.getSid()    + " @" 
      + "\"" 
      + script + "\""; 

String path=context.getReleasePath()+ "/Server/DB Scripts"; 

据执行该文件,但没有退出。因此我尝试使用:

Writer out = new OutputStreamWriter(process.getOutputStream()); 
out.append("commit;\r\n"); 
out.append("exit \r\n"); 
System.out.println("---------"+out); 
out.close(); 

此它完整块我米使用:

if(context.getConnectionField()=="ORACLE") 
{ 

    String cmd= 
    "sqlplus "+ context.getDatabaseUser()  + "/" 
       + context.getDatabasePassword() + "@" 
       + context.getDatabaseHost()  + ":" 
       + context.getDatabasePort()  + "/" 
       + context.getSid()    + " @" 
       + "\"" 
       + script +"\""; 

    String path=context.getReleasePath()+ "/Server/DB Scripts"; 
    process = Runtime.getRuntime().exec(cmd,null,new File(path)); 
    out = new OutputStreamWriter(process.getOutputStream()); 
    out.append("commit;\r\n"); 
    out.append("exit \r\n"); 
    System.out.println("---------"+out); 
    out.close();  

     Integer result1 = null; 
    while (result1 == null) { 
     try { 
      result1 = process.waitFor(); 
    } 
      catch (InterruptedException e) {} 
    } 

    if(process.exitValue() != 0) 
      return false; 
     return true; 
} 
+1

如果您认真对待此问题,请考虑其他人如何阅读您的问题;你的问题格式不好,很难为其他人阅读。通常,这会导致低质量的答案或根本没有答案。如果你想正确回答你的问题,请尝试写下你的问题:) – 2011-05-03 14:38:15

+0

它以什么方式不起作用?你没有得到你期望的结果,或者你是否遇到异常情况等? – karakuricoder 2011-05-03 14:43:06

回答

1

所示的代码无法读取Process的错误流。这可能会阻碍进展。 ProcessBuilder是在Java 1.5中引入的,并且有一个方便的方法来访问redirectErrorStream() - 因此只需要使用单个流。

有关更多一般技巧,请阅读&实施When Runtime.exec() won't的所有建议。

+1

不仅错误,也是输出流。 – krico 2011-05-03 20:53:11

+0

@krico:是的。我实际上认为OP是这样做的,但由于'out.close()'发生在'process.waitFor()'之前,'OutputStream'没有被正确地使用。 – 2011-05-03 21:46:21

0

我可以在这里看到一些问题。您正在使用的'exec'版本将使用StringTokenizer对命令字符串进行标记,因此密码中的不常用字符(如空格)或其他替代参数将等待发生。我建议切换到版本

过程EXEC(的String [] cmdarray, 的String [] envp, 文件目录) 抛出IOException异常

它是更多的工作使用,但更健壮。

第二个问题是关于exec是否会与Java进程同时运行(参见http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html)有各种警告。所以你需要说出你正在使用哪种操作系统。如果它不同时运行,那么写入输出流的策略将无法工作!

程序的最后一位写得比较模糊。我建议......

for (;;) { 
    try { 
     process.waitFor(); 
     return process.exitValue() == 0; 
    } catch (InterruptedException _) { 
     System.out.println("INTERRUPTED!"); // Debug only. 
    } 
} 

这消除了多余的变量RESULT1,消除了多余的拳击和突出无限循环的一个可能的原因。

希望这会有所帮助&祝你好运!

相关问题