Search code examples
javamacosruntime.exec

Java command Runtime.getRuntime().exec() in Mac OS


I´m using Mac OS Lion, with java version 1.6.0_26

I'm making a small app for Mac in Java with a main menu for the user, so he can choose several options.

One of them is install an app using a .pkg

Everything was working fine with these commands:

File instFolder = new File(System.getProperty("user.dir") + "/foldername/appInstaller.pkg");
String s = "open "+ instFolder.toString();
Process p = Runtime.getRuntime().exec(s);

Then I realized that there is a problem when foldername has spaces or if I copy this java file with the needed subfolders to a USB pen drive with "NO NAME" as name (or some name with spaces).

Because s will become something like:

open /Volumes/NO NAME/foldername/appInstaller.pkg
or
open /Users/user1/Desktop/folder name/appInstaller.pkg



So when you run the p process, the command will finish where the first space appears on the path

open /Volumes/NO
or
open /Users/user1/Desktop/folder


To try to fix this I changed the s definition for something like this:

String s = "open "+ "\"" + instFolder.toString() + "\"";

It stopped working fine. The strange thing is that if i copy the s value (after creating the s variable) and paste it in the terminal it works:

open "/Users/user1/Desktop/folder name/appInstaller.pkg"


but running it from Java it does't work.

Could you help me, please?

Thanks.


Solution

  • In order to properly escape arguments, you can use the following:

    Runtime.getRuntime().exec(new String[] { "open", instFolder.toString() });
    

    Though I would probably to use the more modern ProcessBuilder:

    ProcessBuilder pb = new ProcessBuilder("open", instFolder.toString());
    Process p = pb.start();
    int exitCode = p.waitFor();
    

    Though this may be worth a read depending on what you want to do with the processes output.

    Note: edited to reflect question in comment