Unable to load external TTF fonts

For some reason, I cannot load any TTF fonts in my application. Here is a simple example:

File f = new File("/blah/font.ttf");
System.out.println(f.canRead());
System.out.println(f.length());
System.out.println(Font.loadFont(new FileInputStream(f), 20));

Output:

true
52168
null

Font not loaded. I tried different fonts, but none of them worked. What could be the problem? I am running Arch Linux.

$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
+1
source share
1 answer

Assuming you have a package structure in your application, for example

struture

The following code should work

import java.io.InputStream;
import javafx.scene.text.Font;

public class AccessTest {

    public static void main(String[] args) throws URISyntaxException, MalformedURLException {
        InputStream is = AccessTest.class.getResourceAsStream("OpenSans-Regular.ttf");
        Font font = Font.loadFont(is, 12.0);
        System.out.println("Font: " +font);

        File f = new File(AccessTest.class.getResource("OpenSans-Regular.ttf").toURI());

        // should not be used because of f.toURL() is deprecated
        Font font1 = Font.loadFont(f.toURL().toExternalForm(), 12.0);
        System.out.println("Font 1: " + font1);

        Font font2 = Font.loadFont(f.toURI().toURL().toExternalForm(), 12.0);
        System.out.println("Font 2: " + font2);

    }
}

This gives me the following result:

Font: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
Font 1: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
Font 2: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]

If you place a font file outside of your package, there may be an access violation. In your case, the Font.load () method simply splits the appropriate input stream into the construct. It would be a little difficult to get a suitable URL or URI that uses the load method.

+1
source

All Articles