Java class.getRessource().getPath()在URL开头添加了奇怪的’/’。

huangapple go评论105阅读模式
英文:

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

问题

我想在SWT中加载字体。我的ttf文件位于Maven项目的resources/fonts目录中。我尝试这样加载它:

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

但是得到的布尔值始终为false。我尝试提示fontURL.getPath()的结果,它是类似于/C:/Users/myuser/Documents/...的内容。如果我将这个结果复制到一个字符串中,去掉第一个斜杠,然后尝试用它调用display.loadFont(),它就能工作。

另一个奇怪的事情是,不仅这个资源是我以这种方式加载的。例如,这是我加载窗口图标的方式:

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

而且它能够正常工作。唯一导致问题的是字体文件。有人知道为什么吗?

英文:

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 ?

答案1

得分: 2

在路径开头加上/的原因是URL类的getPath方法返回的是由RFC 2396定义的URL路径(参见javadocs)。

至于为什么对于Image构造函数有效而对于loadFont()方法无效,答案可以在实现中找到。
构造函数使用了FileInputStream,它在内部对路径进行了规范化,而loadFont()具有用于加载的本地实现,不支持此类路径。

由于在这两种情况下都期望文件路径,您想要做的是使用File构造函数或Paths.get(url.toURI()).toString()方法自行规范化路径。

英文:

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.

huangapple
  • 本文由 发表于 2020年4月3日 21:36:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61013165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定