javajarshortcutlnk

Create shortcut to .jar using java-code


I wrote an updater for my Java application which downloads its newest jar-file online, replaces the shortcut to it before starting the new jar and finally deleting itself.

I used the following code to create the shortcut:

try {
    //Location of shortcut -> Working
    String address = "C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\App.lnk";

    //Delete old shortcut -> Not working
    File f = new File(address);
    f.delete();

    //Create new shortcut
    FileWriter fw = new FileWriter(address);
    fw.write("[Program]\n"); //Probably wrong section but cannot find real one
    fw.write("FILE=" + (new File(App.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath()) + "App-"+version+".jar\n"); //Shortcut to newest version
    fw.flush();
    fw.close();
} catch (URISyntaxException e) {e.printStackTrace();}

The code does create a file but it seems to be broken so my question is what am I doing wrong here?


Solution

  • This is how it works:

    ShellLink shortcut = ShellLink.createLink("App.jar").setWorkingDir(new File(".").getAbsolutePath());
    shortcut.getHeader().getLinkFlags().setAllowLinkToLink();
    shortcut.saveTo("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\App.lnk");