如何在Java项目中加载本地TTF字体?代码执行遇IO异常求助
解决加载TTF字体时的IOException问题
这个错误的根源很明确:你用classLoader.getResource().getFile()获取的路径是URL编码后的字符串,路径里的空格被转成了%20,但File类无法识别这种编码格式,所以找不到实际的字体文件。
下面给你两种靠谱的解决方案:
方案1:直接使用InputStream加载(推荐)
Font.createFont()方法本身支持直接传入InputStream,完全绕开File路径编码的问题,还能避免文件路径相关的其他坑。代码修改如下:
private void registerFont(){ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // 用try-with-resources自动关闭输入流,避免资源泄漏 try (InputStream fontStream = getClass().getClassLoader().getResourceAsStream("net/utils/ttf/Press Style Extra L.ttf")) { if (fontStream == null) { throw new IOException("找不到指定的字体文件,请检查路径和文件名是否正确!"); } ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, fontStream)); } catch(Exception e){ e.printStackTrace(); } }
方案2:解码URL路径后再用File加载
如果你一定要用File对象来加载,需要先对getResource().getFile()返回的编码路径进行解码,把%20还原成空格:
import java.net.URLDecoder; import java.nio.charset.StandardCharsets; private void registerFont(){ GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try{ URL fontUrl = getClass().getClassLoader().getResource("net/utils/ttf/Press Style Extra L.ttf"); if (fontUrl == null) { throw new IOException("字体资源不存在,请确认classpath中是否包含该文件!"); } // 解码URL路径,把%20转回空格 String decodedPath = URLDecoder.decode(fontUrl.getFile(), StandardCharsets.UTF_8.name()); ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(decodedPath))); } catch(Exception e){ e.printStackTrace(); } }
额外注意事项
- 确保字体文件确实存在于编译后的classpath目录中(也就是你错误信息里的
D:\Client\Client\eclipse\out\production\Client\net\utils\ttf\路径下),文件名和代码里的要完全一致(包括空格和大小写,虽然Windows不区分大小写,但跨平台时要注意)。 - 优先用方案1,因为InputStream的方式更通用,不管资源是在本地文件系统还是打包在Jar里都能正常工作,而方案2只适用于本地文件系统的情况。
内容的提问来源于stack exchange,提问作者Sapu
相关产品推荐
相关产品推荐

