0

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.

2
  • Try to use ProcessBuilder Class and execute your command Commented Jan 11, 2016 at 15:28
  • @MiteshParmar thanks, but can you tell me why this is wrong? Commented Jan 11, 2016 at 15:30

2 Answers 2

1

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.

answered Jan 11, 2016 at 15:36
Sign up to request clarification or add additional context in comments.

1 Comment

There's no "Thank you" on StackOverflow. Just accept the answer :)
0

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();
 }
answered Jan 11, 2016 at 15:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.