【问题标题】:IOexception while running bash commands through ProcessBuilder通过 ProcessBuilder 运行 bash 命令时出现 IOexception
【发布时间】:2013-03-26 20:50:27
【问题描述】:

尝试使用 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();
}

是什么导致进程找不到文件?

【问题讨论】:

  • 您可以尝试使用完整路径运行 sed 二进制文件。

标签: java processbuilder


【解决方案1】:

ProcessBuilder expects individual arguments to be sent separately 在构造函数中。尝试像这样运行它:

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

(如果需要,您也可以将其传递给List<String>

这种方式可以防止shell injection 安全漏洞。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多