不能在Runtime.exec()+ linux中使用&&运算符

Nic*_*ick 3 java linux bash terminal runtime.exec

我正在尝试使用下面粘贴的代码从Java运行可执行文件.通过在终端中使用&&运算符,我可以使用单个命令导航到并运行可执行文件.我试图通过Runtime.getRuntime().exec()命令传递相同的命令,但它似乎不喜欢&&运算符.有谁知道这方面的工作?在下面发布的代码中,我只是将"cd && pwd"作为测试用例; 一个更简单的命令,但它仍然无法正常工作.谢谢

try{
                int c;
                textArea.setText("Converting Source Code to XML");
                //String[] commands = {"/bin/bash", "-c", "cd /home/Parallel/HomeMadeXML", "&&", "./src2srcml --position" + selectedFile.getName() + "-o targetFile.xml"};
                String commands = "bash -c cd && pwd";
                System.out.println(commands);
                Process src2XML = Runtime.getRuntime().exec(commands);
                InputStream in1 = src2XML.getErrorStream();
                InputStream in2 = src2XML.getInputStream();
                while ((c = in1.read()) != -1 || (c = in2.read()) != -1) {
                        System.out.print((char)c);
                    }
                src2XML.waitFor();
                }
            catch(Exception exc){/*src2srcml Fail*/}
            }
Run Code Online (Sandbox Code Playgroud)

tha*_*guy 5

要运行命令,必须使用三个参数:bash可执行文件,-c执行命令的标志和第三个shell命令.

您正在尝试传递5,其中最后三个是一个命令的单个片段.

这是一个例子.注意shell命令只是一个参数:

String[] commands = { "/bin/bash", "-c", "cd /tmp && touch foobar" };
Runtime.getRuntime.exec(commands);
Run Code Online (Sandbox Code Playgroud)

执行时,您将找到foobar在您的文件中创建的文件/tmp.