通过ProcessBuilder运行bash命令时发生java IOexception
尝试使用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 楼答案
构造函数中的
ProcessBuilder
expects individual arguments to be sent separately。试着这样运行:(如果需要,也可以传递
List<String>
)它通过这种方式防止shell injection安全漏洞