0

So lets say I have JAR file. User creates some text file and wants to save it. I would like to save it in "resources" folder in my JAR so user can read it later.

But how do I get path to this folder?

4
  • 1
    It's generally a bad idea to try to manipulate a JAR file while your program is running from that JAR file. It sounds like you have an X-Y Problem -- could you explain more about what your actual problem is, and why you think this is the right way to solve it? Commented Mar 2, 2013 at 22:39
  • I just want to SAVE TEXT FILE to JAR folder. How to do this? Commented Mar 2, 2013 at 22:39
  • The answer to "how to do this?" depends on why you want to do this. Re-stating the question as "I just want to do X" doesn't help. Commented Mar 2, 2013 at 22:42
  • possible duplicate of How can a Java program use files inside the .jar for read and write? Commented Mar 3, 2013 at 0:28

2 Answers 2

3

You usually wouldn't do this. Updating a zip file (which is what a jar file is, basically) is non-trivial. Jar files aren't designed to be updated with user content (e.g. their "documents" directory, or an application-specific directory). You should store your user's files in an appropriate directory. (Heck, in many operating systems the program files are installed read only anyway...)

Sign up to request clarification or add additional context in comments.

3 Comments

But how can I know where to create such folder? In windows I could create it in Program Files but Linux doesnt have such directory. Where to store those files?
@user2102972: No, you shouldn't put it in Program Files in Windows! That's for programs - this is for user content. Ask the user, possibly starting off with their home directory.
The default directory were user-created documents should be stored is a complicated question with a long answer. However, as a minimal effort, you can use Paths.get(System.getProperty("user.home"), "Documents").
1

Not sure if it is a good idea but it is possible from command line (jar command help):

jar cf myfile.jar dir1/file1.ext1 ;# create jar file and store file1 jar uf myfile.jar dir2/file2.ext2 ;# update jar file with file2 

What is possible from command line should be possible thru the Jar Java API

2 Comments

Will the jar command work if the JAR is opened for reading by the JVM? (Also, instead of a command-line solution, there is the JarFile class in the standard library.)
@DanielPryden - it will certainly happily write to the file, and reading JVM will most probably not like it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.