Raphael Roth
Raphael Roth

Reputation: 27373

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

Currently, the code justs run

Upvotes: 5

Views: 4281

Answers (2)

dariober
dariober

Reputation: 9062

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:

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.

Upvotes: 3

SomeDude
SomeDude

Reputation: 14228

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

Upvotes: 0

Related Questions