Reputation: 717
I am getting a IOException when trying to run a sed command through Java using a ProcessBuilder:
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"
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?
Upvotes: 0
Views: 1304
Reputation: 54252
ProcessBuilder
expects individual arguments to be sent separately in the constructor. 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)
It works this way to prevent shell injection security vulnerabilities.
Upvotes: 4