Java command Runtime.getRuntime (). Exec () on Mac OS

I am using Mac OS Lion, with java version 1.6.0_26

I am creating a small Mac application for Java with a main menu for the user, so he can choose several options.

One of them is to install the application using .pkg

Everything worked perfectly 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 the folder name has spaces, or if I copy this java file with the necessary subfolders to a USB drive with the name "NO NAME" as a name (or some name with spaces).

Because s will become something like:

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



So when you start the p-process, the command will end the place where the first place appears in the path

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


To fix this, I changed the definition of s to something like this:

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

He stopped working normally. It is strange that if I copy the value of s (after creating the variable s) and paste it into the terminal, it will work:

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


but starting it from Java, it does not work.

could you help me?

Thanks.

+4
source share
3 answers

To avoid arguments correctly, you can use the following:

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

Although I would probably use a more modern ProcessBuilder :

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

Although this one may be useful for reading, depending on what you want to do with the output of the processes.

Note: edited to reflect the question in the comment.

+5
source

it seems that your path does not have quotes when it turns into a shell.

You should probably add a "" on either side of your path, so the last shell command will look like this:

 open 'your path' 

instead

 open your path 
+1
source

Here's a little trick that came out of the answers mentioned above:

 ProcessBuilder pb = new ProcessBuilder(commandString.split(" ")); 

Say commandString = "killall Mail" , then the split will split the words, making it String[] the ProcessBuilder parameter.

0
source

Source: https://habr.com/ru/post/1379282/


All Articles