与参数列表一起用作单个字符串

与参数列表一起用作单个字符串

本文介绍了将 ProcessBuilder 与参数列表一起用作单个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从 Runtime.exec(command) 切换到 ProcessBuilder 以从 Java 程序执行 ImageMagick 的 convert.convert 的选项是从用户作为字符串传入的,因此我无法轻松地将参数分开以将它们单独传递给 ProcessBuilder 的构造函数.在(Unix)命令行上工作的实际命令是

I try to switch from Runtime.exec(command) to ProcessBuilder for executing ImageMagick's convert from a Java programm. The options for convert are passed-in from the user as a String, so I cannot easily separate the arguments to pass them indvidually to ProcessBuilder's constructor. The actual command that works on the (Unix) commandline is

convert -colorspace gray -enhance -density 300 in.pdf out.pdf

我怎样才能让它发挥作用:

How can I get this could to work:

public class Demo {
    public static void main(String[] args) throws IOException, InterruptedException {
        String convertOptions = "-colorspace gray -enhance -density 300"; // arguments passed in at runtime
        ProcessBuilder bp = new ProcessBuilder(new String []{"convert",convertOptions,"in.pdf","out.pdf"});
        Process process = bp.start();
        process.waitFor();
    }
}

目前,代码刚刚运行

推荐答案

老问题,但由于我面临类似的情况...

Old question but since I'm facing a similar situation...

如果您不想将命令字符串拆分为数组,您可以使用 bash -c 执行整个字符串:

If you don't want to split the command string into an array you could execute the whole string using bash -c:

String convert= "convert -colorspace gray -enhance -density 300";
String[] cmd= new String[] {"bash", "-c", convert};
ProcessBuilder builder = new ProcessBuilder(cmd);
...

这当然假设 bash 可用.

这篇关于将 ProcessBuilder 与参数列表一起用作单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 04:02