Can you store data inside a .jar?

狂风中的少年 提交于 2019-12-06 08:22:48

问题


I'm learning java and am currently trying to develop a simple application. My question is can you store data about settings, etc in a text file internal to a .jar? If so how would you go about accessing this within java? Sorry if this is a really stupid idea.


回答1:


InputStream is = this.getClass().getResourceAsStream("/data/file.txt");

The resources you are getting need to be on the classpath




回答2:


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.




回答3:


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.)



来源:https://stackoverflow.com/questions/16704631/can-you-store-data-inside-a-jar

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