简体   繁体   English

通过ProcessBuilder运行bash命令时的IOexception

[英]IOexception while running bash commands through ProcessBuilder

I am getting a IOException when trying to run a sed command through Java using a 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

The command is sed -i 's/hello world//g' /home/user/test But the problem isn't the command, I can run the same command through terminal and it would remove the string "hello world" 该命令是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();
}

What is causing the process to be unable to find the file? 是什么导致进程无法找到文件?

ProcessBuilder expects individual arguments to be sent separately in the constructor. ProcessBuilder 希望单独的参数在构造函数中单独发送 Try running it like this: 尝试像这样运行它:

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

(You can also pass it a List<String> if you want) (如果需要,还可以将List<String>传递给它)

It works this way to prevent shell injection security vulnerabilities. 它可以通过这种方式来防止Shell注入安全漏洞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM