javafontsswtgetresource

Java class.getRessource().getPath() adds a weird '/' at the begining of the URL


I want to load a font in a SWT. My ttf file is in the resources/fonts directory of my Maven project. I try to load it like this:

URL fontURL = MyClass.class.getResource("/fonts/myfont.ttf");
boolean fontLoaded = display.loadFont(fontURL.getPath());

But the resulting boolean is always false. I tried to prompt the result of fontURL.getPath(), and it is something like /C:/Users/myuser/Documents/.... If I copy this result in a String, remove the first / and try to call display.loadFont() with it, it works.

Another weird thing is that this is not the only resource I load this way. For example, this is how I load the icon of the window:

URL iconURL = MyClass.class.getResource("/images/myicon.png");
Image icon = new Image(display, iconURL.getPath());
shell.setImage(icon);

And it works fine. The only file posing problem is the font file. Does anybody know why ?


Solution

  • The reason for / at the beginning is that getPath of the URL class returns the URL path defined by RFC 2396 (see javadocs).

    As for why it's working for the Image constructor and not for loadFont() method, the answer can be found in the implementation. The constructor uses FileInputStream which internally normalizes the path, whereas loadFont() has a native implementation for loading which does not support such path.

    Since in both cases a file path is expected, what you want to do is normalize the path yourself using either File constructor or Paths.get(url.toURI()).toString() method.