Executing linux shell command using ProcessBuilder
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
Why not execute an array instead of a string?
[“convert”, srcFile, dstFile].execute().waitFor()
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)
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.