[英]Running command in linux environment fails
我正在嘗試通過Runtime.getRuntime().exec()
執行命令。 當我在我的 linux bash 中運行以下命令時,它工作正常。
命令: 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);
}
}
}
我也嘗試使用單引號而不是雙引號。
不幸的是,現在已棄用的Runtime.exec(String)
將此命令錯誤地分解為 4 參數命令{ "bash", "-c", "\"npm", "-v\"" }
。 將參數列表分隔為 3 個參數命令{ "bash", "-c", "npm -v" }
將避免此問題。
使用Runtime.exec
內部使用的ProcessBuilder
更容易:
ProcessBuilder pb = new ProcessBuilder("bash","-c", "npm -v");
Process exec = pb.start();
請注意,您必須在單獨的線程中使用 stdout + stderr。 您上面的內容可能會起作用,但它可能會因其他過程或條件而凍結。 您可以通過重定向到文件或將錯誤重定向到標准輸出來避免:
pb.redirectErrorStream(true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.