Reading files from a folder inside a jar file

I have a jar file that contains various folders such as images, fonts, messages, etc .... I have to read all the files inside the font folder.

Currently, my java code iterates through the entire contents of 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 so that I can specify the path to the font folder (congig-jar \ config \ assets \ fonts), and not navigate through the contents in the bank. I know that the path to the font folder is fixed, so I do not want the overhead of tracing through all the folders in the bank.

+5
source share
2 answers

You can use Classloader to install jar on your classpath. and then all the files inside the jar are downloadable 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
+3

Class.getResourceAsStream( "/pkg/resource_name" );

.

http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html

+1

All Articles