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



我正试图用下面粘贴的代码从Java运行一个可执行文件。通过使用&终端中的操作员I既可以导航到可执行文件,也可以用单个命令运行可执行文件。我试图通过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*/}
            }

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

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

下面是一个例子。注意shell命令只是一个参数:

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

执行时,您会发现在/tmp中创建了一个文件foobar

最新更新