Executing jar file using Java only works on a pc to pc basis

Danny :

I am trying to create a launcher for a Java application that will automatically update/download a jar file in the user home area of a computer, and then proceed to execute it.

I've tried to run the jar file using both the Process and Runtime classes, and I've had nothing but success on my own pc, but it seems that 1:10 people that try this distributed software (also in jar form) can't seem to have the jar file to run (for reference I have ensured that all the people who tested this application had the newest version of Java installed).

The code responsible for running the jar file is as follows:

 public static void startApplication() {
        try {
             Process proc = Runtime.getRuntime().exec("java -jar "+(saveDirectory + fileName));
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

I expected for the jar file fileName to be opened in location saveDirectory, however in a pc to pc scenario this wasn't always the case. I'm just wondering if there is perhaps a better way of doing this that will ensure success 100% of the time.

Karol Dowbecki :

If user.home contains spaces this may not work as the command is evaluated as-is due to being provided as String. Use the Runtime.exec(String[]) version:

Runtime.getRuntime().exec(new String[] { "java", "-jar", saveDirectory + fileName });

Additionally you may want to normalize the JAR path:

Path path = Paths.get(saveDirectory, fileName);
String fullPath = path.normalize().toAbsolutePath().toString();
Runtime.getRuntime().exec(new String[] { "java", "-jar", fullPath });

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92457&siteId=1