简体   繁体   English

将ProcessBuilder与参数列表一起用作单个String

[英]Using ProcessBuilder with argument list as single String

I try to switch from Runtime.exec(command) to ProcessBuilder for executing ImageMagick's convert from a Java programm. 我尝试从Runtime.exec(command)切换到ProcessBuilder以便从Java程序执行ImageMagick的convert 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. 转换的选项是作为String从用户传入的,因此我不能轻易地将参数分开以将它们单独传递给ProcessBuilder的构造函数。 The actual command that works on the (Unix) commandline is 适用于(Unix)命令行的实际命令是

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();
    }
}

Currently, the code justs run 目前,代码只是运行

Old question but since I'm facing a similar situation... 老问题,但因为我面临类似的情况......

If you don't want to split the command string into an array you could execute the whole string using bash -c : 如果您不想将命令字符串拆分为数组,则可以使用bash -c执行整个字符串:

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

This of course assumes bash is available. 这当然假设bash可用。

You could use regex to get your params like in the code below: 您可以使用正则表达式获取您的参数,如下面的代码:

String regex = "((\\s*|-)\\w+)";
Pattern p = Pattern.compile(regex);
String convertOptions = "-colorspace gray -enhance -density 300"; // //arguments passed in at runtime
Matcher matcher  = p.matcher(convertOptions);
List<String> pargs = new ArrayList<String>();
pargs.add("convert");
while(matcher.find())
{
   String match = matcher.group();
   if( match != null )
   {
      pargs.add(match.trim());
   }
}
pargs.add("in.pdf");
pargs.add("out.pdf");

try
{
    ProcessBuilder bp = new ProcessBuilder( pargs.toArray(new String[]{}) );
    Process process = bp.start();
    process.waitFor();
}
catch(Exception ex)
{
  ex.printStackTrace();
}

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

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