简体   繁体   中英

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

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

Its working fine from terminal, The same command can be executed from bin

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

I tried folowing java program to do the above task

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

Output

-ERR "originate Command not found!

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.

Use ProcessBuilder and supply a directory path

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)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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