Can you store data inside a .jar?

☆樱花仙子☆ 提交于 2019-12-04 14:14:22
InputStream is = this.getClass().getResourceAsStream("/data/file.txt");

The resources you are getting need to be on the classpath

jonm

Yes you can, and it's not a stupid question we all need to start somewhere.

There are two parts to your question:

  1. Adding a data/text file to a .jar - (using ant to jar it:) add "fileset dir=..." to the jar target, where dir is set equal to the directory that has the data/text file. Refer to How can I include data text files in a jar using Ant?

  2. Accessing that data/text file from within the java code - you need to use a ClassLoader and getResourceAsStream. Refer to Loading files in JAR in Tomcat using getResourceAsStream

Also, please take a look at https://github.com/gitjonathan/turbo-sansa, I have a working version up on it.

Can you store data inside a .jar?

Read-only data can be stored inside a JAR file. You can read such data using getResourceAsStream(...) if the JAR is on the classpath, or by using the standard JAR file API class if it is not on tle classpath.

But storing update-able data in a JAR file is problematic:

  • In a lot of circumstances it is impossible; e.g. because the JAR file is read-only or was downloaded on the fly.

  • In all other cases it would be very awkward, because the standard JAR file API class does not support update in place. (You would need to create a new ZIP file, copy across the old content apart from the file you are updating, add that file, and then rename the resulting file.)

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