I'm building a Java desktop application and need to store some local data (preferences and history). For this I'd like to create a new folder in the appropriate location, like AppData\myapp in Windows and ~/.myapp in Linux (and wherever is expected on a Mac).
What is the nice, cross-platform way to do that?
I've seen several questions on this site that ask about this, but either:
user.home
(Linux style, not cross-platform) This is what I currently do, but I'm looking for an improvement.You could always use the Java Preferences API which will store info per-user and you don't have to worry about the implementation. Different implementations are available for different platforms but that's hidden from you (the client).
An alternative is to use the Apache Commons Configuration API, which is more complex, but gives you a lot more features.
import java.io.File;
public class AppPathFolder {
public static void main(String[] args) {
String path = null;
String osName = System.getProperty("os.name").toLowerCase();
if (osName.indexOf("windows")>-1) {
path = System.getenv("APPDATA");
} else if (osName.indexOf("mac")>-1) {
// get the env. variable for Mac..
path = System.getenv("?");
// etc. for Linux, Unix, Solaris..
} else { //anything else
path = System.getProperty("user.home");
}
File rootOfPath = new File(path);
// create a sub-directory based on package name of main class..
// perhaps prefixed with with java/appdata
System.out.println(rootOfPath);
}
}
Of course, there are other options for small amounts of data:
Preferences
APIPersistenceService
- available even to sand-boxed apps.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With