shell命令执行从Java执行时失败 [英] shell Command execution Failing when executed from Java
本文介绍了shell命令执行从Java执行时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在命令行上执行以下命令时,它显示了sybase DB中的所有存储过程和表。
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
但是当我在java做同样的事情。这不返回任何结果。任何人都可以告诉我下面的代码有什么问题:
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
我按照Darkdust的建议执行它,但仍然无法正常工作。
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);
}
但命令如下:
sh -c 'printf "sp_help\ngo\n" | isql -Usa -Psybase11 -Dcnadb'
可在命令行中使用。
我也试过:
p = Runtime.getRuntime().exec(new String[]{"sh","-c","\'printf \"sp_help\ngo\n\"","|isql -Uxx -Pxxxxx -Dxxxxx\'"});
但没有成功。
推荐答案
有几件事情想起来了:
- 不完整的PATH环境变量(因此
isql
找不到)。 - 如果它是一个命令,你提供,而不是搞乱PATH,你可能想确保你是在正确的工作目录并调用
./ isql
。 - 由于你使用管道,你应该让shell执行这个
sh -cfoo | bar
。否则| isql ...
部分作为参数传递给printf
。
- 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 toprintf
as well.
这篇关于shell命令执行从Java执行时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文