DEV Community

loading...

Can you create "resources" in .jar files in Java?

baenencalin profile image Calin Baenen ・1 min read

I know there's a .getResource(String name) method in Java, but is there like a .setResource(String name, File f), or something like that, in Java?
I'm asking because I want to create a save file, but I don't want the user to see them (unless the purposefully try to find it).

Thanks!
Cheers!

Discussion (12)

pic
Editor guide
Collapse
pjotre86 profile image
pjotre86

Do you want to store it in the jar you're actually running or a different one?

Collapse
baenencalin profile image
Collapse
pjotre86 profile image
pjotre86

Then I'm afraid it's not possible at all. Can't change a file which is in use...

Thread Thread
baenencalin profile image
Calin Baenen Author

Is there any way to do it if the .jar is not in use?

Thread Thread
pjotre86 profile image
pjotre86

Yes, there is. A jar is effectively just a zip file. So you can unzip it, change/add stuff and zip it again. Feels a bit hacky, but should work.

Thread Thread
baenencalin profile image
Calin Baenen Author

How do I unzip/zip a .jar file programmatically?

Thread Thread
pjotre86 profile image
Thread Thread
baenencalin profile image
Calin Baenen Author

Thank you for your help.

Collapse
alainvanhout profile image
Alain Van Hout

You could also create a file and make it hidden, as e.g. described in javacodeexamples.com/make-file-hid....

I wouldn't advise using your jar file for storage. That's not what it is meant for and as such you'll likely encounter more and more difficulties along the way.

Collapse
baenencalin profile image
Calin Baenen Author

Okay, well, then I should probably go about encoding the data?

Because, if possible, I want to do all I can to prevent file tampering.

Thanks for the suggestion, it really helps!

Collapse
alainvanhout profile image
Alain Van Hout

There are a number of ways to do that. This might be a reasonable starting point: baeldung.com/java-cipher-input-out...

Thread Thread
baenencalin profile image
Calin Baenen Author

Thanks for this.
Cheers!