Extracting files from a Jar more efficently

南笙酒味 提交于 2019-12-04 16:41:54

Opening a JAR is a very expensive operation. So you may want to open the JAR once and keep the JarFile instance in a static field somewhere. In your case, you will also want to read all entries and keep them in a hashmap for instant access of the resource you need.

Another solution is to put the JAR on the classpath and use

DivineFont.class.getContextClassLoader().getResource*("/8.png");

Mind the "/"! If you omit it, Java will search in the same directory (package) in which it finds the file DivineFont.class.

Getting things from the classpath has been optimized to death in Java.

Well, I found the answer. The answer to my original question was "Wrong question." The Jar file wasn't the issue, it was the library I was using to load the images.

When I was loading from the file system, the image was being named "38.png", etc. When I was loading from the Jar, I was simply naming it "38".

The Image loader class inside the library uses the file extension of the name to identify which image loader to use. If there is no file extension, it uses a slower, basic image loader. When I changed this line:

buffer = new AngelCodeFont(String.valueOf(number), fntFileStream, pngFileStream );

to this line:

buffer = new AngelCodeFont( number + ".png", fntFileStream, pngFileStream );

We have ourselves a winner.

Thanks for the help anyway guys. It took me a few hours to figure this out, but if not for your posts, I probably would have continued to assume the blame was Java's rather than the Library I'm using.

Jar file manipulation can be very expensive, and the Java class library already implements this kind of resource loading (probably as efficiently as possible.)

Plus, once you're in webstart, your jar file names will get mangled, so you'll likely end up having to explore every jar file on the classpath to load your resources (I've done it! Ugly!)

Instead, use Class.getResourceAsStream(String resourceName). I haven't profiled it, but I haven't noticed it being noticeably slower than direct file access.

This library may not compress as much as you need, but it'll be faster...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!