2015-10-07 61 views
0

我正在运行使用Java的命令并且没有输出。使用Java运行Linux命令时出现问题?

Process p; 
Runtime run = Runtime.getRuntime(); 
    String s1 = "queryData 1005017 --format '\"%s" scope'"; 

    System.out.println("Command is " + s1); 


    try { 

     p = run.exec(s1); 
     BufferedReader br = new BufferedReader(
       new InputStreamReader(p.getInputStream())); 
      while ((s = br.readLine()) != null) 
       System.out.println("line: " + s); 
     p.getErrorStream(); 
     p.waitFor(); 

    } 

while the command ---> queryData 1005017 --format''%s“scope'runs without any issue。想知道是否在处理双引号或%符号时丢失了任何内容?

+1

假设你丢失的反斜杠只是一个错字(?没有你的程序编译),你尝试过检查'p.exitValue()'了'waitFor'后,看它是否终止成功或没有? – RealSkeptic

+0

是的,这是错字。我得到的退出值是退出:1 – Ammad

+0

因此退出失败。尝试阅读错误流而不是输入流,看看它给你带来了什么样的错误。 – RealSkeptic

回答

2

请不要使用字符串从Java启动进程。正确的方法是使用ProcessBuilder

p = new ProcessBuilder(Arrays.asList(
    "queryData", "1005017", "--format", "\"%s\" scope")).start(); 
+0

谢谢。解决这个问题。 – Ammad

2

你没有正确转义内部引号:

String s1 = "queryData 1005017 --format '\"%s" scope'"; 
      ^--start java string    ^--end java string 
               ^^^^^ what's this mean to java? 

你可能想

String s1 = "queryData 1005017 --format '\"%s\" scope'"; 
              ^--note this 

代替。

+2

那么,这不会编译,OP说它不会返回输出。也许这只是一个错字。 – RealSkeptic

+0

是的,这是排字错误 – Ammad