启动jar时,控制台会说找不到文件,也没有加载字体。我该如何解决这个问题?
我得到了这个代码:
public class FontLoader {
public static Font load(){
String fontFilePath = Paths.get(System.getProperty("user.dir"), "prova.jar", "Retro Gaming.ttf").toString();
int fontStyle = Font.BOLD;
int fontSize = CenterOnDefaultScreen.center().height*2/100;
Font font = null;
int fontTypeResource = Font.TRUETYPE_FONT;
if((fontFilePath == null || fontFilePath.isEmpty()) || fontSize < 1) {
throw new IllegalArgumentException("load() Method Error! Arguments " +
"passed to this method must contain a file path or a numerical " +
"value other than 0!" + System.lineSeparator());
}
try {
font = Font.createFont(fontTypeResource, new FileInputStream(
new File(fontFilePath))).deriveFont(fontStyle, fontSize);
}
catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException: " + fontFilePath);
}
catch (FontFormatException | IOException ex) {
System.out.println("Exception thrown");
}
return font;
}
}
String fontFilePath = Paths.get(System.getProperty("user.dir"), "prova.jar", "Retro Gaming.ttf").toString();
那。。显然是行不通的。
您需要使用gRAS(getResourceAsStream(系统。java中的File
(与中一样,new FileInputStream
需要的是java.io.File
对象(是实际的文件。jar文件中的条目不计算在内。不可能用File
对象引用ttf文件,也不可能用FileInputStream打开它。
幸运的是,createFont
方法不要求您传递FileInputStream
;任何旧的InputStream
都可以。
ttf文件需要和您正在编写的这个类(例如,同一个jar(在同一个类路径根中。一旦你确保了这一点,你就可以使用gRAS:
try (var fontIn = FontLoader.class.getResourceAsStream("/Retro Gaming.ttf")) {
Font.createFont(Font.TRUETYPE_FONT, fontIn).deriveFont(.., ...);
}
gRAS与FontLoader.class
所在的位置相同。从您的代码片段中,听起来您将ttf放在jar的"根"中,而不是放在FontLoader旁边。getResourceAsStream
的字符串参数中的前导斜杠表示:相对于FontLoader所在位置的根进行查找(因此,可能是您的jar(。