简体   繁体   中英

Execute a shell command line in Java

I tried to execute a shell command in Java, but it's not working.

I can directly run this command on Linux(Ubuntu):

/bin/sh -c 'while true ; do java -jar /home/user/workspace/TCPClientNew/WebContent/NewClient.jar  192.168.138.1 6789 ; sleep 1 ; done'

but when I do this with Java, it never executes. It always shows "Not Found". Here is my code:

Runtime rt = Runtime.getRuntime();
Process proc;

String[] commands = {"/bin/sh","-c","'while true ; do java -jar /home/user/workspace/TCPClientNew/WebContent/NewClient.jar "+" "+host+" "+port+ " ; sleep 1 ; done'"};
proc = rt.exec(command);

Can someone tell me why it's wrong? Thank you very much.

The single quotes in the command line are there to prevent interpretation of the third argument by the shell that runs the command line. They are not needed in Java, as there's no command line shell anymore. Just remove the single quotes.

Try to use this code might helps you.

 try {
            ProcessBuilder pb = new ProcessBuilder("/usr/bin/bash", "-c", "while true ; do java -jar /home/user/workspace/TCPClientNew/WebContent/NewClient.jar"+" "+host+" "+port+ " ; sleep 1 ; done");
            pb.start();
            } finally { 
         //  pb.close();
        }

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