繁体   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