簡體   English   中英

通過ProcessBuilder運行bash命令時的IOexception

[英]IOexception while running bash commands through ProcessBuilder

嘗試使用ProcessBuilder通過Java運行sed命令時,出現IOException:

ERROR: java.io.IOException: Cannot run program "sed -i 's/hello world//g' 
/home/user/test": error=2, No such file or directory

該命令是sed -i 's/hello world//g' /home/user/test但問題不是該命令,我可以通過終端運行同一命令,它將刪除字符串“ hello world”

public void removeString(String str, String file) throws IOException {
    String command = "sed -i \'s/" + str + "//g\' " + file;
    System.out.println(command);
    ProcessBuilder pb = new ProcessBuilder(command);
    Process p = pb.start();
}

是什么導致進程無法找到文件?

ProcessBuilder 希望單獨的參數在構造函數中單獨發送 嘗試像這樣運行它:

ProcessBuilder pb = new ProcessBuilder("sed", "-i", "s/hello world//g", "/home/user/test");

(如果需要,還可以將List<String>傳遞給它)

它可以通過這種方式來防止Shell注入安全漏洞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM