获取字体文件作为 File 对象或获取其路径
我在 Java 中有一个用于字体文件的 Font 对象。我需要将该对象转换为文件对象或获取字体文件路径。
有办法做到这一点吗?
我在这里所做的是从外部库调用一个方法,该方法加载字体文件以在书写中使用它:
loadTTF(PDDocument pdfFile, File fontfile);
所以我想让用户从操作系统中定义的字体中选择一种字体,使用:
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts();
然后当用户选择时一种字体,我将其传递给 loadTTF(...)
方法来加载它。
这里有不好的做法吗?
I have a Font object in Java for a font file. I need to convert that object to a File object or get the font file path.
Is there a way to do this?
What I'm doing here is calling a method from an external library that loads a font file to use it in writing:
loadTTF(PDDocument pdfFile, File fontfile);
So I wanted to let the user choose a font from the ones defined in his operating system using :
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts();
Then when the user chooses a font, I pass it to the loadTTF(...)
method to load it.
Is there a bad practice here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的...这将返回字体文件路径:
我已经在 Windows 和 Linux 中尝试过,并且在两者中都运行良好。
Ok ... This will return the font file path :
I have tried this in Windows and Linux and in both it worked fine.
不。
Java 中的 Font 只是如何以图形方式显示字符的表示和定义。它与文件系统无关,从技术上讲,甚至不需要最终在文件中定义(例如,请参见 createFont() 方法采用任意输入流,该输入流可以来自任何地方,例如网络套接字)。无论如何,如果您能够获取定义字体的底层系统文件的路径,这肯定是一个荒谬的抽象突破。
我建议,如果您依赖于接受文件,您可能在其他方法中做错了事情。或者,如果确实需要这样做,那么您在 this 方法中就犯了错误,认为
Font
对象与底层文件具有简单的关联。如果您确实需要获取特定字体的文件路径,则需要从不涉及 java.awt.Font 的不同角度来处理它。No.
A Font in Java is just a representation and definition of how characters can be displayed graphically. It has nothing to do with the filesystem, and technically need not even be ultimately defined in a file (see for example the createFont() method that takes an arbitrary input stream, which could come from anywhere e.g. a network socket). In any case, it would certainly be a ridiculous break in abstraction for you to be able to get the path of the underlying system file that defines the font.
I would suggest that you might be doing the wrong thing in your other method if you're relying on accepting a file. Or if this really is needed, then you're doing the wrong thing in this method by thinking that a
Font
object has a simple correlation to an underlying file. If you really need to get the file path of a particular font you'll need to approach it from a different angle that doesn't involve java.awt.Font.