简体   繁体   English

在Java中执行Shell命令行

[英]Execute a shell command line in Java

I tried to execute a shell command in Java, but it's not working. 我试图在Java中执行Shell命令,但无法正常工作。

I can directly run this command on Linux(Ubuntu): 我可以在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. 但是当我使用Java执行此操作时,它永远不会执行。 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. 命令行中的单引号用于防止运行命令行的shell解释第三个参数。 They are not needed in Java, as there's no command line shell anymore. 在Java中不需要它们,因为不再有命令行外壳。 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();
        }

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

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