Java Language Getting sub-nodes of Preferences


Preferences objects always represent a specific node in a whole Preferences tree, kind of like this:

├── com
│   └── mycompany
│       └── myapp
│           ├── darkApplicationMode=true
│           ├── showExitConfirmation=false
│           └── windowMaximized=true
└── org
    └── myorganization
        └── anotherapp
            ├── defaultFont=Helvetica
            ├── defaultSavePath=/home/matt/Documents
            └── exporting
                ├── defaultFormat=pdf
                └── openInBrowserAfterExport=false

To select the /com/mycompany/myapp node:

  1. By convention, based on the package of a class:

    package com.mycompany.myapp;
    // ...
    // Because this class is in the com.mycompany.myapp package, the node
    // /com/mycompany/myapp will be returned.
    Preferences myApp = Preferences.userNodeForPackage(getClass());
  2. By relative path:

    Preferences myApp = Preferences.userRoot().node("com/mycompany/myapp");

    Using a relative path (a path not starting with a /) will cause the path to be resolved relative to the parent node it is resolved on. For example, the following example will return the node of the path /one/two/three/com/mycompany/myapp:

    Preferences prefix = Preferences.userRoot().node("one/two/three");
    Preferences myAppWithPrefix = prefix.node("com/mycompany/myapp");
    // prefix          is /one/two/three
    // myAppWithPrefix is /one/two/three/com/mycompany/myapp
  3. By absolute path:

    Preferences myApp = Preferences.userRoot().node("/com/mycompany/myapp");

    Using an absolute path on the root node will not be different from using a relative path. The difference is that, if called on a sub-node, the path will be resolved relative to the root node.

    Preferences prefix = Preferences.userRoot().node("one/two/three");
    Preferences myAppWitoutPrefix = prefix.node("/com/mycompany/myapp");
    // prefix            is /one/two/three
    // myAppWitoutPrefix is /com/mycompany/myapp