【问题标题】:IOException When Loading Java Font加载 Java 字体时出现 IOException
【发布时间】:2019-02-27 12:42:18
【问题描述】:

我正在为一个班级编写的国际象棋程序实现一个 GUI。为了让它看起来更漂亮,我想使用从互联网上获得的 Chess Piece Font。

文件 chess.ttf 位于路径 Chess/resources/chess.ttf。我根据 Oracle 的指令 (https://docs.oracle.com/javase/tutorial/2d/text/fonts.html) 使用以下代码:

try {
            File file = new File("resources/chess.ttf");

            //Returned font is of pt size 1
            Font font = Font.createFont(Font.TRUETYPE_FONT, file);

            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, file)); 

            //Derive and return a 12 pt version:
            //Need to use float otherwise
            //it would be interpreted as style

            return font.deriveFont(12f);
        } 

    catch (IOException|FontFormatException e) {
        System.out.println("-Font Error-");
        return null;
    }

但是,这会引发 IOException。我在文件上运行 getAbsolutePath() 并收到 /Users/[me]/eclipse-workspace/Chess/resources/chess.ttf 所以我假设文件正在正确加载。有谁知道我的代码出了什么问题?

编辑:问题解决了吗?我按照建议尝试了 InputStreams,但没有奏效,但在恢复我的代码后,计算机终于停止抛出 IOExceptions。代码不是最好的吗?

【问题讨论】:

  • 尝试使用Class#getResourceClass#getResourceAsStream“我在文件上运行 getAbsolutePath() 并收到 /Users/[me]/eclipse-workspace/Chess/resources/chess.ttf 所以我假设文件” - File 是“抽象”表示,不能保证 File 实际存在于指定位置 - 为此使用 exists
  • 扩展@MadProgrammer 评论的前面部分。应用程序资源将在部署时成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。

标签: java fonts awt embedded-resource ioexception


【解决方案1】:

您最好使用 ant 或 maven 等构建脚本复制 ttf /Users/[me]/eclipse-workspace/Chess/bin/resources

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    System.out.println(loader.getResource(".").getPath()); // for tracing the working folder only
    java.io.InputStream ins = loader.getResourceAsStream("resources/chess.ttf");
    //Returned font is of pt size 1
    Font font = Font.createFont(Font.TRUETYPE_FONT, ins);

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2018-06-03
    • 2013-01-05
    相关资源
    最近更新 更多