记一次maven 打包导致字体不可用问题

本文介绍如何在Java中使用自定义字体,并解决Maven打包时字体文件损坏的问题。通过调整pom.xml中的资源文件配置,确保字体文件正确打包。避免使用过滤功能,直接排除fonts目录,保持字体文件完整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码
 

public class HaiyanFontUtil {

    private static Font definedFont = null;

    public static Font getDefinedFont(String type, float size) {
        String fontUrl = Thread.currentThread().getContextClassLoader()
        .getResource("").getPath() + "fonts" + File.separator + type;
        if (definedFont == null) {
            try {
                File file = new File(fontUrl);
                definedFont = Font.createFont(Font.TRUETYPE_FONT, file);
                definedFont = definedFont.deriveFont(size);
            } catch (FontFormatException | IOException e) {
                e.printStackTrace();
                return new java.awt.Font("宋体", Font.PLAIN, 50);
            }
        }
        return definedFont;
    }

    public static void main(String[] args) {
        Font font = getDefinedFont("STXINGKA.TTF", 50);
    }
}


如果 pom.xml 

<resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
 </resources>


则会导致 字体文件 打包时 损坏不可用

修改

<resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>fonts/**</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>fonts/**</include>
                </includes>
            </resource>
 </resources>


过滤时排处 fonts 文件夹下的 文件

参考
 Maven 打包 项目中的资源文件损坏打不开 https://blog.csdn.net/qing_mei_xiu/article/details/80661216
 Java引用外部字体即自定义字体文件 https://blog.csdn.net/nahancy/article/details/75482418

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值