Executing linux shell command using ProcessBuilder

29 / Dec / 2011 by Divya Setia 3 comments

We often need to execute linux shell command from our groovy code. What I had to do in my project was to resize the image saved on file system.

I was doing something like :

[java]String command = "convert -adaptive-resize ${width}x${height}! ${sourceFilePath} ${destinationFilePath}"
Process process=command.execute()
process.waitFor()
[/java]

The above code makes a new image file with specified width and height of image. The problem I encountered was that the above code doesnot work for files having spaces in their name e.g. file name “new house.jpg”

Then by googling I found ProcessBuilder which is a utility class that interact with OS from java program and create OS processes.

[java]ProcessBuilder pb = new ProcessBuilder("convert", "-adaptive-resize", "${width}x${height}!", sourceFilePath, destinationFilePath);
Process p = pb.start()
p.waitFor()
[/java]
It works seemlessly!!!

@Divya Setia
divya@intelligrape.com
http://www.intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Luca

    Hi,
    in this blog
    you can find how to use .execute() with spaces …

    Little example follow

    // show the command and then his execution outputs (list of a sub dir with spaces)

    String lParam = “./test\\ Dir/”
    // or
    // String lParam = “\”./test\ Dir/\””

    String command = “sh -c ls -la $lParam”
    println(“[$command]”)
    Process process=command.execute()
    process.waitFor()
    println(process.text)

    Reply
  2. Matthias

    You have to enclose the params that do have spaces in double quotes, something along those lines:

    String command = “””convert -adaptive-resize “${width}x${height}”! “${sourceFilePath}” “${destinationFilePath}””””

    That’ll do the trick.

    Reply

Leave a Reply to balor123 Cancel reply

Your email address will not be published. Required fields are marked *