简体   繁体   中英

Can you store data inside a .jar?

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.

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

您获得的资源需要在类路径上

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM