简体   繁体   中英

IOexception while running bash commands through ProcessBuilder

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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