Java wrapper for Windows registry API RegSetValueEx() Creates a value if it didn't exist or will overwrite existing value - Java Native OS

Java examples for Native OS:Windows

Description

Java wrapper for Windows registry API RegSetValueEx() Creates a value if it didn't exist or will overwrite existing value

Demo Code


//package com.java2s;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.prefs.Preferences;

public class Main {
    /**/*w  w w.  j  a  va 2s. c  o  m*/
     * Error because acces to the specified key was denied
     */
    public static final int ERROR_ACCESS_DENIED = 5;
    private static final Preferences systemRoot = Preferences.systemRoot();
    private static Method windowsRegSetValueEx = null;

    /**
     * Java wrapper for Windows registry API RegSetValueEx()
     * Creates a value if it didn't exist or will overwrite existing value
     * 
     * @param hKey
     *            the Native Handle to the key
     * @param valueName
     *            The name of the value as a byet array
     * @param value
     *            The new vaue to be set as a byte array
     * @return The error code
     */
    public static int RegSetValueEx(int hKey, byte[] valueName, byte[] value) {
        try {
            return ((Integer) windowsRegSetValueEx.invoke(systemRoot,
                    new Object[] { new Integer(hKey), valueName, value }))
                    .intValue();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ERROR_ACCESS_DENIED;
    }

    /**
     * Java wrapper for Windows registry API RegSetValueEx()
     * Creates a value if it didn't exist or will overwrite existing value
     * 
     * @param hKey
     *            the Native Handle to the key
     * @param valueName
     *            The name of the value as a byet array
     * @param value
     *            The new vaue to be set as a byte array
     * @return The error code
     */
    public static int RegSetValueEx(int hKey, String valueName, String value) {
        return RegSetValueEx(hKey, stringToByteArray(valueName),
                stringToByteArray(value));
    }

    /**
     * Returns this java string as a null-terminated byte array
     */
    public static byte[] stringToByteArray(String str) {
        byte[] result = new byte[str.length() + 1];
        for (int i = 0; i < str.length(); i++) {
            result[i] = (byte) str.charAt(i);
        }
        result[str.length()] = 0;
        return result;
    }
}

Related Tutorials