Figuring out where to store local files in Java

For reasons that I think are outside the scope of this question, I want to port a program I wrote for use with Java Web Start to stop using JWS and distribute it as a regular Jar file.

My main problem with this plan is how to figure out where to store files nicely in Java, assuming I will be working on different platforms (although I rely on JOGL too, so there is not much risk of working on horribly esoteric platforms, by at least). My program stores various local data, mainly for caching or "caching" purposes - it's nice to be able to save it, but it's not a complete disaster if data is lost.

I am currently using JNLP PersistenceService

for this purpose, so moving from JWS I need to figure out some directory to store the files. Consider this:

File datadir = new File(System.getProperty("user.home"), ".myprogram");

      

I suppose this works well on Unix and Unix-like platforms, but it is clearly ugly on at least some platforms like Windows where I assume I should be using a directory AppData

or whatever it caused again.

My current thought is to use this datadir

as the default, drop it everywhere except on known platforms where I replace it with something better like Windows. The questions I have about this are the following:

  • Is this a reasonable default to start with? I am fine with this failure on some unknown platforms; I'll just turn off caching and some advanced features if that's the case, but can it somehow get out of the way due to a bad result?
  • Is there a good way to find out if I'm on Windows? The best I can figure out now is to match some patterns with os.name

    which I believe should work well enough, but is there a better way? I'm not trying to fix errors with reflection to see if there are any packages sun.*

    that might help or something (at risk of falling back to defaults) if that's okay. (The question applies in general to all platforms, are there any more solid idioms to figure this out at all?)
  • Is there a good way to find the directory to be used on Windows? Using static paths seems ugly as I know they can be overridden by registry settings or localized and whatever.
  • Are there any other platforms I should be thinking about from the start? Mine datadir

    should work fine on OSX, shouldn't it?
  • Is there any better alternative?
+3


source to share


2 answers


If it just caches data that can be replaced, then I would simply recommend using the temp directory.

Cm:

new File(File.createTempFile().getParent(), 'my-file-name');

      



You can turn it off when you disable the app, or just leave it there.

If you want more semi-persistent, but from storage, you may need to take care of what OS you are on and act accordingly, as t his question answers

+1


source


Consider using the java.util.prefs.Preferences API for this purpose.



+1


source







All Articles