Reputation: 135
I have a jar file, that holds various folders like images, fonts, messages etc... I have to read all the files inside the font folder only.
At present my java code is iterating through all the contents in the jar file. My code is as follows:
private void loadApplicationSpecificFonts() {
try{
JarFile jarFile = new JarFile("owenstyle-jar-config.jar");
JarEntry entry;
String fontName;
for(Enumeration em = jarFile.entries(); em.hasMoreElements();) {
String s= em.nextElement().toString();
if(s.endsWith("ttf")){
fontName= s.substring(s.lastIndexOf("/")+1);
fontName= fontName.substring(0, fontName.indexOf(".ttf"));
entry = jarFile.getJarEntry(s);
InputStream input = jarFile.getInputStream(entry);
Font font= Font.createFont(Font.TRUETYPE_FONT, input);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
input.close();
}
}
jarFile.close();
}catch (IOException e){
System.err.println("Error: " + e.getMessage());
}catch (FontFormatException e){
System.err.println("Error: " + e.getMessage());
}
}
Is there a way such that I can give the path of the font folder(congig-jar\config\assets\fonts), rather than traversing through all the contents in the jar. I know the path of the font folder is fixed, so I do not want the overhead of travesring through all the folders in the jar.
Upvotes: 5
Views: 3059
Reputation: 4799
You can utilize a Classloader to put the jar on you classpath. and then all files inside the jar are loadable resources.
//ref to some jar
File f = new File("/tmp/foo.jar");
//create a new classloader for this jar
URLClassLoader loader = URLClassLoader.newInstance(new URL[]{f.toURI().toURL()});
//load resource with classloader
InputStream inputStream = loader.getResourceAsStream("foo/bar/test.txt");
//...do stuff with inputStream
Upvotes: 3
Reputation: 56
you can use
Class.getResourceAsStream ("/pkg/resource_name");
this code will start to search for resources from the classpath.
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
Upvotes: 1