尝试使用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();
}
是什么导致进程无法找到文件?
答案 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安全漏洞。