java不能识别汉字,Java不能读取字体

Ok, so I have a problem using a custom font. Basically I get a custom font I downloaded off the internet and use it in my program. When I run the program in Eclipse (the editor I use), everything works fine, and there is no problem. BUT, whenever I export it to a jar from eclipse, or try to run it from the command prompt I get this very annoying error:

java.io.IOException: Can't read REVOLUTION.ttf

at java.awt.Font.createFont(Unknown Source)

at TowerDefense.(TowerDefense.java:55)

at TowerDefense.main(TowerDefense.java:302)

I get that along with a bunch of null pointer exceptions because of where I use the font. But I don't know why it says it can't read it. Here is the code that creates the font:

try {

revolution = Font.createFont(Font.TRUETYPE_FONT, new File("REVOLUTION.ttf"));

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

ge.registerFont(revolution);

}

catch (Exception e) {

e.printStackTrace();

}

FOLDER LAYOUT

TowerDefense

src

default package

TowerDefense.java

Game.java

DragTest.java

JRE System Library

REVOLUTION.ttf

neuropol.ttf

解决方案

You can not access contents of a JAR using File API.

You have to load the font file using Classloader's getResourceAsStream method. For this to work you'll have to put the font file on classpath.

So you code becomes:

revolution = Font.createFont(Font.TRUETYPE_FONT, getClass().getClassLoader().getResourceAsStream("REVOLUTION.ttf"));

If font is included inside a package or folder in JAR, then path would change accordingly.

getResourceAsStream("com/example/font/REVOLUTION.ttf"); // if font is present inside com.example.font package

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值