我使用Java 1.8和IntelliJIdea。要使用该程序,我下载了字体
InputStream is1 = GameField.class.getResourceAsStream("assets/fonts/ARIALN.ttf");
private Font myArialNarrow;
{
try {
myArialNarrow = Font.createFont(Font.TRUETYPE_FONT, is1);
} catch (FontFormatException e) {
System.out.println("error1");
e.printStackTrace();
} catch (IOException e) {
System.out.println("error2");
e.printStackTrace();
}
}
private Font myFont1 = myArialNarrow.deriveFont(30f);
结果是,我的字体myFont1的大小为30。在IDE中运行该程序时,一切正常,但是如果我执行jar操作,文件将引发异常:
error2
java.io.IOException: Problem reading font data.
at java.awt.Font.createFont0(Font.java:1000)
at java.awt.Font.createFont(Font.java:877)
at com.pumaex.GameField.<init>(GameField.java:57)
at com.pumaex.LinesLauncher.main(LinesLauncher.java:5)
Exception in thread "main" java.lang.NullPointerException
at com.pumaex.GameField.<init>(GameField.java:70)
at com.pumaex.LinesLauncher.main(LinesLauncher.java:5)
为什么程序找不到字体文件?我写错了路吗?告诉我,怎么了?
已添加
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Problem {
public static Font loadFile(String filePath) throws IOException, ClassNotFoundException, FontFormatException {
try (final InputStream is = new BufferedInputStream(Problem.class.getClassLoader().getResourceAsStream(filePath))) {
return Font.createFont(Font.TRUETYPE_FONT, is);
}
}
public static void main(String[] args) throws Exception {
Font font = loadFile("assets/fonts/ARIALN.ttf");
Font myFont1 = font.deriveFont(30f);
System.out.println(myFont1);
}
}