shell Command execution Failing when executed from Java

只谈情不闲聊 提交于 2019-12-02 21:02:01

问题


When I execute the below command on command line, it shows all the stored procedures and tables in the sybase DB.

printf 'sp_help\ngo\n' | isql -Uxx -Pxxxx -Dxxxxx

But when I do the same thing in java. This does not return any result. Can anyone tell me what is the problem with my code below:

public class test
{
  public static void main(String[] args)
  {
   String cmd = "printf "+"\'sp_help\ngo\n\'"+"| isql -Uxx -Pxxxx -Dxxxxx" ;
   try{ 
          Process p;
          p = Runtime.getRuntime().exec(cmd);
          p.waitFor();
          String line; 
          BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

           while ((line = reader.readLine())!=null){
           System.out.println("Row is :" + line);
   } catch(Exception e)
       {
           System.out.println("Exception Caught : " + e);
       }

  }

}

EDIT I executed it as below suggested by Darkdust but still it doesnt work.

try{
          Process p;
          p = Runtime.getRuntime().exec("sh -c \'printf \"sp_help\ngo\n\" | isql -Uxx -Pxxxxx -Dxxxxxx\'");
          p.waitFor();
          String line;
          BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

           while ((line = reader.readLine())!=null){
           System.out.println("Row is :" + line);
  }
 }
       catch(Exception e)
       {
           System.out.println("Exception Caught : " + e);
       }

But the command :

sh -c 'printf "sp_help\ngo\n" | isql -Usa -Psybase11 -Dcnadb'

Works on command line.

I also tried with :

p = Runtime.getRuntime().exec(new String[]{"sh","-c","\'printf \"sp_help\ngo\n\"","|isql -Uxx -Pxxxxx -Dxxxxx\'"});

But with no sucess.


回答1:


Several things come to mind:

  • Incomplete PATH environment variable (thus isql can't be found).
  • If it's a command you provide, instead of messing with PATH you might want to make sure your are you in the correct working directory and call ./isql instead.
  • Since you're using a pipe, you should let a shell execute this as in sh -c "foo | bar". Otherwise the | isql ... part is passed as argument to printf as well.


来源:https://stackoverflow.com/questions/18081080/shell-command-execution-failing-when-executed-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!