通过ProcessBuilder运行bash命令时发生IOexception

时间:2013-03-26 20:50:28

标签: java 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();
}

是什么导致进程无法找到文件?

1 个答案:

答案 0 :(得分:3)

构造函数中的

ProcessBuilder expects individual arguments to be sent separately。尝试像这样运行它:

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

(如果需要,您也可以传递List<String>

它以这种方式防止shell injection安全漏洞。