我正在尝试通过Runtime.getRuntime().exec()执行一个命令。当我在linux中运行以下命令时,它可以正常工作。
命令:bash -c "npm -v"
但是,当我尝试使用Java运行它时,它会失败,但会出现以下错误:
-v": -c: line 0: unexpected EOF while looking for matching `"'
-v": -c: line 1: syntax error: unexpected end of file可复制的例子:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class RunACommandTest
{
public static void main(String[] args)
{
try
{
Process exec = Runtime.getRuntime().exec("bash -c \"npm -v\"");
new BufferedReader(new InputStreamReader(exec.getInputStream(), StandardCharsets.UTF_8))
.lines()
.forEachOrdered(line -> System.out.println("IN " + line));
new BufferedReader(new InputStreamReader(exec.getErrorStream(), StandardCharsets.UTF_8))
.lines()
.forEachOrdered(line -> System.out.println("ERR " + line));
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
}我也尝试用单引号代替双引号。
发布于 2022-07-27 09:23:50
不幸的是,现在不推荐的Runtime.exec(String)错误地将此命令拆分为4个参数命令{ "bash", "-c", "\"npm", "-v\"" }。将参数列表分隔为3个参数命令{ "bash", "-c", "npm -v" }将避免此问题。
使用ProcessBuilder更容易,Runtime.exec在内部使用
ProcessBuilder pb = new ProcessBuilder("bash","-c", "npm -v");
Process exec = pb.start();请注意,您必须在单独的线程中使用stdout + stderr。上面的内容可能有效,但对于其他过程或条件,它可能会冻结。您可以通过重定向文件或将错误重定向到stdout来避免:
pb.redirectErrorStream(true);https://stackoverflow.com/questions/73135197
复制相似问题