MansNotHot
MansNotHot

Reputation: 293

Awesome Fonts: "pr0blem reading font data" in Java

My goal is to be able to use awesome fonts an a Java GUI. For that matter I searched and found this question.

I chose the second answer to import fontawesome-webfont.ttf with an InputStream. I tailored the code to my needs because I do not need a method for my purpose.

But when it comes to testing it, I get the error: "Problem reading font data" in the line:

Font font = Font.createFont(Font.TRUETYPE_FONT, is);

This is the problematic code:

try (InputStream is = this.getClass().getResourceAsStream("C:/Users/Prak01/Documents/EclipseWorkspace/Zeiterfassung/fontawesome-webfont.ttf")) {
    try {
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        font = font.deriveFont(Font.PLAIN, 24f);
        TextfieldFont = new JTextField("");
        TextfieldFont.setFont(font);
    } catch (FontFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }   
}

I believe that I did everything according to the rules. The data path is correct. Could it be possible that it is because of the...

this.getClass().getResourcesAsStream();

because I changed it from:

TestFontAwsome.class.getResourceAsStream();

but I believe that it should work with this.getClass() as well.

Upvotes: 1

Views: 920

Answers (1)

VGR
VGR

Reputation: 44328

You have mistakenly assumed that the argument to getResourceAsStream is supposed to be a file name. It is not a file name; it’s a relative URL which is resolved against each entry in the classpath. Generally, this means it should be a path in the same .jar file.

If you want to load a Font directly from a File, don’t use getResourceAsStream. Just open it as a file:

try (InputStream is = new BufferedInputStream(
    Files.newInputStream(Paths.get("C:/Users/Prak01/Documents/EclipseWorkspace/Zeiterfassung/fontawesome-webfont.ttf")))) {

Note: You don’t need two try blocks. A try-with-resources statement is allowed to have a catch block:

try (InputStream is = new BufferedInputStream(
    Files.newInputStream(Paths.get("C:/Users/Prak01/Documents/EclipseWorkspace/Zeiterfassung/fontawesome-webfont.ttf")))) {

    // ...

} catch (FontFormatException e1) {
    // ...
}   

Upvotes: 3

Related Questions