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.
-
Try to use ProcessBuilder Class and execute your commandM S Parmar– M S Parmar2016年01月11日 15:28:09 +00:00Commented Jan 11, 2016 at 15:28
-
@MiteshParmar thanks, but can you tell me why this is wrong?EagerToLearn– EagerToLearn2016年01月11日 15:30:57 +00:00Commented Jan 11, 2016 at 15:30
2 Answers 2
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
choroba
245k27 gold badges221 silver badges304 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
choroba
There's no "Thank you" on StackOverflow. Just accept the answer :)
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
M S Parmar
9848 silver badges22 bronze badges
Comments
default