Read/write to Windows registry using Java

前端 未结 24 1611
日久生厌
日久生厌 2020-11-21 05:45

How is it possible to read/write to the Windows registry using Java?

24条回答
  •  一向
    一向 (楼主)
    2020-11-21 06:31

    The java.util.prefs package provides a way for applications to store and retrieve user and system preferences and data configuration. These preference data will be stored persistently in an implementation-dependent backing stored. For example in Windows operating system in will stored in Windows registry.

    To write and read these data we use the java.util.prefs.Preferences class. Below code shows how to read and write to the HKCU and HKLM in the registry.

    import java.util.prefs.Preferences;
    
    public class RegistryDemo {
        public static final String PREF_KEY = "org.username";
        public static void main(String[] args) {
            //
            // Write Preferences information to HKCU (HKEY_CURRENT_USER),
            // HKCU\Software\JavaSoft\Prefs\org.username
            //
            Preferences userPref = Preferences.userRoot();
            userPref.put(PREF_KEY, "xyz");
    
            //
            // Below we read back the value we've written in the code above.
            //
            System.out.println("Preferences = "
                    + userPref.get(PREF_KEY, PREF_KEY + " was not found."));
    
            //
            // Write Preferences information to HKLM (HKEY_LOCAL_MACHINE),
            // HKLM\Software\JavaSoft\Prefs\org.username
            //
            Preferences systemPref = Preferences.systemRoot();
            systemPref.put(PREF_KEY, "xyz");
    
            //
            // Read back the value we've written in the code above.
            //
            System.out.println("Preferences = "
                    + systemPref.get(PREF_KEY, PREF_KEY + " was not found."));
        }
    }
    

提交回复
热议问题