简体   繁体   English

如何从Java在特定目录中执行终端命令

[英]How to execute terminal command in specific directory from java

I am trying to execute originate command in specific directory "/usr/local/freeswitch/bin", In bin I have to run executable file fs_cli by ./fs_cli command, In fs_cli I have to execute following command 我试图在特定目录“ / usr / local / freeswitch / bin”中执行Origin命令,在bin中,我必须通过./fs_cli命令运行可执行文件fs_cli,在fs_cli中,我必须执行以下命令

originate loopback/1234/default &bridge(sofia/internal/1789)

Its working fine from terminal, The same command can be executed from bin 它可以从终端正常工作,可以从bin执行相同的命令

./fs_cli -x "originate loopback/1234/default &bridge(sofia/internal/1789)"

I tried folowing java program to do the above task 我尝试以下java程序来完成上述任务

Process pr = Runtime.getRuntime().exec("./fs_cli -x \"originate loopback/1234/default &bridge(sofia/internal/1789@192.168.0.198)\"");
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
    System.out.println(str);
}

I have creted symbolic link of fs_cli and placed in current location The above program is showing following output 我已将fs_cli的符号链接创建并放置在当前位置,上面的程序显示以下输出

Output 输出量

-ERR "originate Command not found! -ERR“原始命令未找到!

As far as I am concerned whwn above command is working fine with terminal it should be the same from java, So it shows I am wrong somewhere Please help me to sort out this problem. 就我而言,以上命令在终端上运行正常,应该与Java相同,因此它表明我在某个地方出错,请帮助我解决此问题。

Use ProcessBuilder and supply a directory path 使用ProcessBuilder并提供directory路径

ProcessBuilder pb = new ProcessBuilder(
        "./fs_cli",
        "-x",
        "originate loopback/1234/default &bridge(sofia/internal/1789@192.168.0.198)");
pb.directory(new File("..."));
Process pr = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
    System.out.println(str);
}

Where possible, you should provide the command arguments as separate String s, this will pass each as a separate argument to the process and take care of those arguments that need to be escaped by quotes for you (unless it's expecting the quotes, then you should include them anyway) 在可能的情况下,您应该将命令参数作为单独的String提供,这会将每个参数作为单独的参数传递给流程,并照顾那些需要用引号引起来的参数(除非期望引号,否则您应该包括它们)

The other way is: 另一种方法是:

ProcessBuilder processBuilder = new ProcessBuilder( "/bin/bash", "-c", "cd /usr/local/freeswitch/bin && ./fs_cli -x \"originate loopback/1234/default &bridge(sofia/internal/1789)\"" );
processBuilder.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM