gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:49:08 25 4
gpt4 key购买 nike

我正在尝试使用下面粘贴的代码从 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*/}
}

最佳答案

你想运行一个命令,你必须使用三个参数:bash 可执行文件,-c 执行命令的标志,以及第三个 shell 命令.

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

这是一个例子。请注意 shell 命令如何只有一个参数:

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

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

关于java - 不能在 Runtime.exec() + linux 中使用 && 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com