获取首选项的子节点

Preferences 对象总是代表整个 Preferences 树中的特定节点,有点像这样:

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

要选择/com/mycompany/myapp 节点:

  1. 按照惯例,基于类的包:

    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. 按相对路径:

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

    使用相对路径(不以/开头的路径)将导致路径相对于其解析的父节点被解析。例如,以下示例将返回路径/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. 按绝对路径:

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

    在根节点上使用绝对路径与使用相对路径没有区别。不同之处在于,如果在子节点上调用,则将相对于根节点解析路径。

    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