Can't Read *.ttf File

2019-07-27 09:57发布

问题:

I'm programming a dictionary for a language I'm creating. The language does not use any English letters, so I created my own font using free online software at http://www.myscriptfont.com/, which would hopefully allow me to use my language's symbols. The first step to make this dictionary would then be to import this custom font, but it's not working. Here's the part of the code where I import it:

    /**
     * Constructor for class Bank
     */
    public Bank() throws Exception
    {
        //Previous code creates frame and pane with no problems

        try{
            font1 = Font.createFont(Font.TRUETYPE_FONT, new File("fonts/ShoriPart1.ttf"));
        }
        catch(IOException|FontFormatException e){
        }
        font1 = font1.deriveFont(Font.PLAIN, 20);
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(font1);
        JList fonts = new JList(ge.getAvailableFontFamilyNames());
        JOptionPane.showMessageDialog(null, new JScrollPane(fonts));
        JLabel l = new JLabel("The quick brown fox jumps over the lazy dog. 0123456789");
        l.setFont(font1);
        pane.add(l);
        frame.pack();

        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

Every time I ran this, it threw the java.io.IOException "Can't read fonts\ShoriPart1.ttf (in java.awt.Font)." I used try/catch to try to prevent that, but it ended up just not creating the font at all. Is there something wrong with the font file? Is there a way to fix this in the code?

Edit: I just tried using the font in Microsoft Word, and it worked fine.

回答1:

Try using inputStream to pass it to createFont function: see if it works!

InputStream myStream = new BufferedInputStream(new FileInputStream("font.ttf"));
ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);

It happened to me once and passing the stream worked. Don't know actual reason though



回答2:

First tip: NEVER HAVE EMPTY CATCH BLOCKS. At a bare minimum, you should print the stack trace to System.out, but preferable re-throw it. Bypassing the exception like this is just bad.

Assuming the exception message is the literal string you copied, you may want to make sure that the program can read the folder the file is in (i.e. has permission). If it does, then it most likely is an issue with the file format.