尝试将 TTF 文件加载到我的游戏时出现读取字体数据错误的问题

Problem reading font data error when trying to load a TTF file into my game

当我使用 fontLoader class 加载字体时(下面的代码)出现错误:java.io.IOException:读取字体数据时出现问题。

这是我正在开发的一款 2D 游戏。我试过其他加载字体的方法,但没有任何效果。

这是我使用 loadFont 方法的字体 class。


package dev.java2dgame.gfx;

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.File;

public class Fonts {

    public static Font loadFont(String path, float size){
        try {
            return Font.createFont(Font.TRUETYPE_FONT, Font.class.getClass().getResourceAsStream(path)).deriveFont(Font.PLAIN, size);
        } catch (FontFormatException | IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }
}

这是我调用 loadFont() 方法的地方和我输入的路径。它在我的资产 class 中加载并保存我所有的游戏资产。我知道字体文件的路径是正确的,因为我确定并且可以从字体文件夹加载其他图像和东西作为测试。我还检查了 10 遍以确保我写了正确的名字。

public class Assets {

    public static final int width = 64, height = 64;

    public static BufferedImage nothing, floor, aud_floor, gym_floor,
    front_wall, left_wall, right_wall, shelf_wall, whiteboard_wall, closed_window,
    storm_window, bookshelf1, bookshelf2;

    public static Font font36;

    public static BufferedImage saw;

    public static SpriteSheet tileSheet;

    public static void init() {
        font36 = Fonts.loadFont("/fonts/munro.ttf", 16);
        tileSheet = new SpriteSheet("/sprites/tilesheet.png");
        saw = ImageLoader.loadImage("/sprites/singlesprites/woodshop_saw.png");

        nothing = tileSheet.crop(width, height, width, height);

此 class 的其余部分被截断,因为不需要其中的信息。

这是我在 运行 代码时遇到的错误。

java.io.IOException: Problem reading font data.
    at java.desktop/java.awt.Font.createFont0(Font.java:1183)
    at java.desktop/java.awt.Font.createFont(Font.java:1052)
    at dev.java2dgame.gfx.Fonts.loadFont(Fonts.java:12)
    at dev.java2dgame.gfx.Assets.init(Assets.java:21)
    at dev.java2dgame.main.Game.init(Game.java:54)
    at dev.java2dgame.main.Game.run(Game.java:93)
    at java.base/java.lang.Thread.run(Thread.java:835)

我能够使用此代码解决问题![​​=11=]

public static Font loadFont(String path, float size){   
        try {
            InputStream fileStream = Fonts.class.getResourceAsStream(path);
            Font myFont = Font.createFont(Font.TRUETYPE_FONT, fileStream);
            return myFont.deriveFont(Font.PLAIN, size);
        } catch (FontFormatException | IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }