问题
I'm writing a java application. Currently this produces a file called "trace.txt" in the same directory the .jar file lives. This can sometimes cause issue with file permissions, eg writing to C:\Program Files\Foo\trace.txt.
After a bit of research on SO it seems the general opinion is to log to Application Data\Foo\ for the given user. This won't be the same location for other OS's.
What's the best practice in this situation? I'm using java.util.logging.
回答1:
You could always use the USER_HOME, identified by ~ in Linux or
System.getProperty("user.home"); in java.
You'll see lots of apps have their own .myappname folder, and put config files, logs in there.
This will map to /home/user/.myapp in linux or C:/Documents and settings/user/.myapp in windows, and should always be writable.
回答2:
If this is a "real" log or trace file, I would write it to the Default temp file path that you can get via the java.io.tmpdir
system property.
回答3:
If your java program require "installation" (it may be just set up some configuration files, move you binary to certain place etc), then it is perfectly fine to handle permission stuff (in what ever platform) during installation or other platform specific stuff for whatever log files, configurations, caches user settings etc. Installation usually implies user has to run the installation script/program with superuser privilege. So, you can do so.
Generally if your application store user specific data you may store it to /home//. in Linux like system and Users\ttchong\AppData in Window 7 for example (I am not very familiar in Window, correct me if I am wrong). And your code also need to handle the user path to allow multiple users have different settings of your program.
Else, if it is program information like log files that you don't mind to dump together I still prefer the way you do it now, store it with the same directory of your jar file or a little better in a log folder in the same directory by using the "installation" trick.
来源:https://stackoverflow.com/questions/3275359/how-to-choose-the-location-of-a-log-file-for-a-java-application-in-a-platform-in