开发者

What's a good place to save a file to in a Java app?

I have a Web Start application which needs to save a single text file. I would like to know where I shoul开发者_如何学God write the file, such that it goes in a tidy place regardless of the platform it runs on.

If I get my filepath like this...

new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "test.txt);

... then the file gets written somewhere nice and inconspicuous on Linux, but on the desktop on Windows, alongside the icon I'm running the program from, and that's not ideal because the user shouldn't necessarily need to know or care that the file exists.

Is there a good, platform-independent way of getting a file path that allows me to save a file somewhere discreet? I don't much care where it ends up, providing it's not in full view on the desktop.

Thanks.

Neil


user.dir is the current working directory; use user.home instead and java.io.tmpdir for temporary files.

Here's the list of predefined properties for Java 1.5.


What about using a .yourapp directory under user.home instead? You shouldn't face any permission problem, a windows user won't really notice it, it would be hidden on GNU/Linux.

For temporary stuff, you may prefer java.io.tmpdir but keep in mind that the content of this directory (/tmp on GNU/Linux) might be wiped out upon reboot (e.g. with Debian distros). So this is really for temporary stuff.

PS: I prefer to use File.separator over System.getProperty("file.separator").


I strongly suggest using the PersistenceService.


If you don't need the file per user or to be incredibly permanent you can use System.getProperty("java.io.tmpdir"));


As others have stated, "user.home" is a decent choice. If you can get away with it, Preferences are another good choice for storing certain things.

If you do end up using something like "user.home" then make sure you have a fallback position. I've been in many situations where a user's home directory was not writable (locked down windows installs under a domain server for example).

If you store data in the "user.home" directory then put it under a ".myApp" style sub-directory and first verify that you can create that directory. If you cannot create that directory then you could always prompt the user for a place to store it. And then store that location in a system Preference so that it's known the next time the app is run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜