Mohammad Jafar Mashhadi
Mohammad Jafar Mashhadi

Reputation: 4251

Is writing into class resources a good way to save files?

When we want to load a static file e.g. a picture, a sound file, a file containing information about a game map,... we can store them as resources in jar file and use getClass.getResource("images/splash.png") (also getResourceAsStream) to load and use them. But when we want to read and write into a file like settings file, I don't think using resources is a good way, because i think resources are designed to store read/only files that are not supposed to change, like splash screen image or a game's background music; These are my reasons to think this way:

  1. That is why return value of getResourceAsStream is an instance of InputStream and we don't have a similar function which gives us an OutputStream, because we're not supposed to alter resource files.
  2. Writing into resources changes program .jar file and i guess it's not a good thing at all; Because if we do so: we can't use check-sums to verify file, if we are a limited user and system administrator doesn't give us write permission we can't make changes into main .jar file, user-specific preferences are hard or impossible to implement,...

So, my questions are:

  1. Which parts of my thoughts and assumptions are right or wrong?
  2. If they're right what is the best(I mean short and portable between OSs and Computers) way to store files like that? (Application setting/preferences, A game save file, ...)

(@Some user who may wants to mark this as duplicate: I don't think my question is a duplicate, i searched in the site, I admit it has some common parts with some questions but it's not duplicate!)

Upvotes: 0

Views: 318

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86459

Your three observations in #2 above are valid reasons not to store settings in a resource file, regardless of the APIs provided.

There are a variety of ways to save settings in Java, including:

  • The Java system property "user.home" provides the user's home directory, to which the user should have write access. You can create an application-specific subdirectory underneath it.
  • Java provides a Preferences API. This may store settings in a directory or (on Windows) in the registry.
  • OSGI provides a preferences API.
  • If you're using the Eclipse RCP, you can write to the configuration directory using a ConfigurationScope. See the Eclipse FAQ "What is a preference scope").

Upvotes: 4

Related Questions