One problem which has been puzzling me for weeks now is how I can create a shortcut file from Java. Now before I say anything else, I have looked all over Google (and also on this site; including this: Creating shortcut links (.lnk) from Java) trying to find something helpful. What I need isn't an installer package which creates a shortcut, but to create a shortcut from code. What I mean by shortcut is a .lnk file which are usually found on the Desktop.
One of the helpful things I found was this program:
Java Code:
import java.io.*;
public class WindowsUtils {
private WindowsUtils() { }
private static final String WINDOWS_DESKTOP = "Desktop";
public static String getWindowsCurrentUserDesktopPath() { //return the current user desktop path
return System.getenv("userprofile") + "/" + WINDOWS_DESKTOP ;
}
public static void createInternetShortcutOnDesktop(String name, String target) throws IOException {
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, "");
}
public static void createInternetShortcutOnDesktop(String name, String target, String icon) throws IOException {
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, icon);
}
public static void createInternetShortcut(String name, String where, String target, String icon) throws IOException {
FileWriter fw = new FileWriter(where);
fw.write("[InternetShortcut]
");
fw.write("URL=" + target + "
");
if (!icon.equals("")) {
fw.write("IconFile=" + icon + "
");*
}
fw.flush();
fw.close();
}
public static void main(String[] args) throws IOException {
WindowsUtils.createInternetShortcutOnDesktop("GOOGLE", "http://www.google.com/");
}
}
I toyed around with it, and managed to create a .lnk shortcut on my desktop. However, I foudn two problems:
I couldn't change the icon, despite the path linking it to a correct icon.
I made a path which led me to C:/Users/USER/Documents, however, whenever I clicked the shortcut it took me to C:/. When I delete the shortcut, the dialogue shows me indeed that the path is file:////C:/Users/USER/Documents.
I know that this code above was originally meant to create Internet Shortcuts, so I believe I might have taken the wrong approach. I would appreciate any help/links you can give me.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…