Read/write to Windows registry using Java

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

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

24条回答
  •  甜味超标
    2020-11-21 06:24

    Java Native Access (JNA) is an excellent project for working with native libraries and has support for the Windows registry in the platform library (platform.jar) through Advapi32Util and Advapi32.

    Update: Here's a snippet with some examples of how easy it is to use JNA to work with the Windows registry using JNA 3.4.1,

    import com.sun.jna.platform.win32.Advapi32Util;
    import com.sun.jna.platform.win32.WinReg;
    
    public class WindowsRegistrySnippet {
        public static void main(String[] args) {
            // Read a string
            String productName = Advapi32Util.registryGetStringValue(
                WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
            System.out.printf("Product Name: %s\n", productName);
    
            // Read an int (& 0xFFFFFFFFL for large unsigned int)
            int timeout = Advapi32Util.registryGetIntValue(
                WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows", "ShutdownWarningDialogTimeout");
            System.out.printf("Shutdown Warning Dialog Timeout: %d (%d as unsigned long)\n", timeout, timeout & 0xFFFFFFFFL);
    
            // Create a key and write a string
            Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, "SOFTWARE\\StackOverflow");
            Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, "SOFTWARE\\StackOverflow", "url", "http://stackoverflow.com/a/6287763/277307");
    
            // Delete a key
            Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, "SOFTWARE\\StackOverflow");
        }
    }
    

提交回复
热议问题