2

Is there a platform-independent way to get a path to store program data in Java?

This is surely a very basic question but I can't seem to find the answer anywhere. I am looking for a path to store user data such as user preferences or historical data input. On Windows we would normally store it in C:\Program Files\APPNAME, C:\Program Files (x86)\APPNAME or C:\ProgramData\APPNAME depending on the OS and architecture. On Unix we could store preferences in /etc/APPNAME or /opt/APPNAME depending on the context. On Mac we have a special cabinet to store program's data. In java, how do we get a location like this in a platform-independent way?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Adam Burley
  • 5,551
  • 4
  • 51
  • 72
  • Duplicate of http://stackoverflow.com/questions/11113974/what-is-the-cross-platform-way-of-obtaining-the-path-to-the-local-application-da ? – Rag Jan 02 '14 at 15:15

2 Answers2

2

Look to store settings in a (sub-)directory of user.home. Not only is it a place to which the app. would reasonably be expected to have read-write privileges, but is cross-platform.

The sub-directory might be based on the Fully Qualified name or package name of the class to prevent clashes. I.E.

package our.com.main;

Would be written to sub-directory our/com/main.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

The system property user.home should be pretty standard across most desktop systems.

System.out.println(System.getProperty("user.home"));

Note that this is the user the Java process runs under - so in case of server-side Java process, you would need to store information for the users of your app in your own data structure, as your app's users are not known to the OS.

Regarding a system-wide storage location, you may need to detect the OS version and compute the path. Another problem is that you would most likely need to escalate privileges to write to a system-wide location.

Akber Choudhry
  • 1,755
  • 16
  • 24