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

5

39

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.

Torrietorrin answered 19/2, 2011 at 17:23 Comment(0)
K
101

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?

Kristenkristi answered 19/2, 2011 at 17:32 Comment(0)
M
3

This is not really supported. In principle, you could operate on the jar file, but there's no guarantee the new contents would be correctly loaded. Let your build tools manage the jar file -- and choose something else for persistent storage managed by your program itself. Like a file.

Marney answered 19/2, 2011 at 17:26 Comment(0)
P
2

It is unlikely that you can change a loaded jar safely. Changing it while it is being used is not a good idea.

If you want to do this, use a plain file system directory and add/remove files from it. Even this may not work as you expect.

Permanence answered 19/2, 2011 at 17:32 Comment(0)
L
2

You can manipulate any jar file using the package java.util.jar (or indeed just java.util.zip). As files inside a jar will be compressed, this isn't the most time efficient way for you to store data.

You should probably use a directory somewhere else (e.g. System.getProperty("user.home") + "/.myProgram") or see java.util.prefs.

Locarno answered 19/2, 2011 at 17:34 Comment(0)
L
1

Class.getResource() returns a URL. Theoretically, you can use this URL to create your InputStream and OutputStream. But in most cases, the generated JAR is a read-only file (or archive). So your application might trip when trying to use it.

Lundt answered 15/4, 2012 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.