5

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

2
  • 3
    Split convertOptions with " " as delims and use them to construct convertOptions? If you pass the whole string , it will consider whole string as a parameter. Its not what you want I presume. Commented Feb 6, 2016 at 14:57
  • you are right of cause, but I do not need to split on " ", but on "-" Commented Feb 8, 2016 at 6:51

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.