Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a local storage directory in Java desktop app

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:

  • The asker wants to find Windows' Application Data (not cross-platform)
  • The solution is to create a folder in user.home (Linux style, not cross-platform) This is what I currently do, but I'm looking for an improvement.
like image 457
Bart van Heukelom Avatar asked Jun 21 '12 13:06

Bart van Heukelom


2 Answers

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.

like image 175
Brian Agnew Avatar answered Nov 20 '22 15:11

Brian Agnew


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:

  • Apps. that are trusted or have no security manager might use the Preferences API
  • A desktop app. launched using Java Web Start has access to the JNLP API, wich offers the PersistenceService - available even to sand-boxed apps.
  • An applet can store cookies.
like image 36
Andrew Thompson Avatar answered Nov 20 '22 16:11

Andrew Thompson