Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an app use files inside the JAR for read and write?

I need to store data into files inside .jar file and read it again.

I know that I can use Class.getResourceAsStream() method but it returns an InputStream that I can read from. But I look for a way to write.

like image 409
Moataz Aahmed Mohammed Avatar asked Feb 19 '11 17:02

Moataz Aahmed Mohammed


People also ask

How do I access files inside a JAR?

You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead. Show activity on this post. You could read the contents of a JAR file using the JarFile class. Show activity on this post.

What apps use JAR files?

Coral WinZip is the best option for opening the JAR file since it is available for almost all platforms and is easy to use. You can also use WinRAR or 7-Zip if you have them pre-installed on your system.

How is a JAR file used?

JAR files are packaged with the ZIP file format, so you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. These tasks are among the most common uses of JAR files, and you can realize many JAR file benefits using only these basic features.

Can we read code that is in JAR file?

Hi, Jar files are archive files that contains of a lot of different java classes (files). You can use winzip/winrar to open the jar files and you can see those java classes in jar files. Typically you can use a Java decompiler to decompile the class file and look into the source code.


1 Answers

I need to store data into files inside .jar file and read it again

No you don't.

Instead store the 'default' file inside the Jar. If it is changed, store the altered file in another place. One common place is a sub-directory of user.home. When checking for the file, first check the existence of an altered file on the file system, and if it does not exist, load the default file.


Note that it is generally better to describe the goal, rather than the strategy. 'Store changed file in Jar' is a strategy, whereas 'Save preferences between runs' might be the goal.

Related: What is the XY problem?

like image 76
Andrew Thompson Avatar answered Sep 23 '22 00:09

Andrew Thompson