Access the Win32 registry in jdk1.4

Source: Internet
Author: User
Tags integer numbers

The Java language has been selected by many programmers for its platform independence. If it is used to operate the registry, it seems to have lost this feature. However, in actual programming, sometimes we need to store software information in the Registry to facilitate initialization or check registration information at next startup (assuming we are on Windows )! So can I use Java to operate the Windows registry?

The Java. util. prefs package has been provided since jdk1.4, with a preferences class that can help us operate the system registry. The Preferences class has different implementation methods on different platforms. On Windows, preferences stores data in the registry, while on other platforms, preferences stores data in files, directory services, or databases. But in any case, they are all used through the same interface. The programmer can ignore the specific storage implementation details. Finally, I will explain the following points:
1: Do not use uppercase letters for your node. Otherwise, a "/" is added before the entry in the registry.
2: The values in the Registry can also be imported into an XML file. For details, see the relevant documentation.
3: If preferences pre = preferences in the Code is set. systemroot (). node ("/javaplayer"); Replace with preferences pre = preferences. userroot (). node ("/javaplayer"); then the corresponding HKEY_LOCAL_MACHINE becomes hkey_local_user

On Windows, the root node of the USER parameter entry in the registry is HKEY_CURRENT_USER/software/Embedded oft/prefs; the root node of the system parameter entry in the registry is HKEY_LOCAL_MACHINE/software/Embedded oft/prefs; the node paths we specify are located under these root nodes. Java cannot directly operate the Windows registry, where Java. util. the preferences class in prefs can only operate some registries. the root directory obtained by systemroot () is not the Registry root directory (eg: hkey_classes_root), but a Java-defined system directory "/" (for example: may be "/" = HKEY_CURRENT_USER/software/kerberoft/prefs ).

The following class can add an item zzti and item value under HKEY_CURRENT_USER/software/systoft/prefs, and save the added information to the zzti. xml file.

Import java. util. prefs .*;
Import java. Io .*;
Class testregedit {
Public static void main (string [] ARGs)
{
Preferences mynode = preferences. userroot (). node ("zzti ");
System. Out. println (mynode. absolutepath ());
String [] keys = {"com", "name", "Age "};
String [] values = {"IBM", "gongshi", "20 "};
For (INT I = 0; I <keys. length; I ++)
{
Mynode. Put (Keys, Values);
}
Try {
Mynode. exportnode (New fileoutputstream (new file ("zzti. xml ")));
}
Catch (exception E)
{
E. printstacktrace ();
}

// The following section deletes an entry in the registry.
/* Try {
Mynode. removenode ();
}
Catch (backingstoreexception E)
{
E. printstacktrace ();
}*/
}
}

 

 

Added for Java 1.4. util. the prefs package allows you to operate user preference data and configuration data by providing access to the specific registry (for example, the Windows registry on Windows.

Do you have to save the configuration data of the program but do not know where to store the data? Although you can obtain this information using attribute files or resource bundles, the Java platform has never specified a standard location for storing these files. After JSR 10 appears, everything changes. It provides the added java. util. prefs package for Java 1.4 APIs. The storage mechanism is specific to implementation details, but programmers do not have to know or worry about it. For Windows platforms, the location is "Windows Registry ". Although you cannot control the registry, you can access all applications through a public root node.

  Start

The appropriate preferences class provides a basic framework for operating preferences. This class provides a series of static and abstract methods to operate on one of the two sets of preferences (one is user preferences and the other is system preferences. With the static method, you will get a platform-specific implementation, just like the windowspreferences class. Then you can use the abstract method of the platform-specific implementation to do this work.

Grouping program preferences with a package is a good habit to avoid naming conflicts with other applications. When you search for a preferences object, you only need to pass the package name. When using a non-static method, you can pass a reference to itself (this), and the program will determine which package you are looking for, as shown in Listing 1.

Listing 1. Getting preferences objects from non-static methods

Preferences userprefs = preferences. usernodeforpackage (this );
Preferences sysprefs = preferences. systemnodeforpackage (this );

However, if you are using a static method, you must obtain the root node and provide your own package, as shown in Listing 2.

Listing 2. Getting preferences objects from static methods

Preferences userprefs = preferences. userroot (). node ("/NET/zukoski/IBM ");
Preferences sysprefs = preferences. systemroot (). node ("/NET/zukoski/IBM ");

With the nodes for operation, you can easily set, retrieve, remove, and dump settings. You only need to treat the preferences object as a large key-value Hash (this table organizes the keys in the tree structure ). But it is not a part of the collection framework. (For more information about the collection framework, see references ).

Author: Peter Source: forum responsible editor: Fangzhou [] provides Registry access for the java. util. prefs package added by Java 1.4

  Write Data

We will start from discussing how to store preferences. The preferences class provides a series of put () methods for storing values as follows. In addition to supporting basic strings, you can also store Boolean values, double-precision numbers, floating-point numbers, integer numbers, long integer numbers, and byte arrays (serialization is considered ). The Helper method uses appropriate data types and performs necessary conversions to store data as strings.

Put (string key, string value)
Putboolean (string key, Boolean value)
Putbytearray (string key, byte value [])
Putdouble (string key, double value)
Putfloat (string key, float value)
Putint (string key, int value)
Putlong (string key, long value)

All put () Methods return a void. If the storage mechanism is unavailable, a backingstoreexception is thrown.

Note: The key length of a specific preference is limited to preferences. max_key_length (80) characters, and its value is limited to preferences. max_value_length (8192) characters.

  Read data

You can use the following get () methods to obtain specific preferences. Similar to writing data, each supported data type has its own unique method. However, unlike obtaining data, you must provide the default value when the backup storage is unavailable or some items are not saved. This requires you to make sure that your program has at least reasonable default settings.

Get (string key, string default)
Getboolean (string key, Boolean default)
Getbytearray (string key, byte default [])
Getdouble (string key, double default)
Getfloat (string key, float default)
Getint (string key, int default)
Getlong (string key, long default)

If you are not sure about the preference name, you can use the keys () method to find a column of keys associated with the node. This method returns the string [] of the node. In addition to obtaining and storing individual preferences and obtaining a column of keywords, you can also use clear (), remove (), and removenode () to remove nodes and values.

  Dump data

If you want to save and restore preferences outside of the backup storage provided by the system, you can perform these operations in the XML format document. You can use exportnode () to export a node or use exportsubtree () to export the entire subtree. Information is stored in UTF-8 format. Then, you can use the importpreferences () method to restore information.

  Listen

"Curiosity will kill a cat", but if you are interested in clearing the preference when it changes, you can register a nodechangelistener or preferencechangelistener without considering the consequences. Nodechangelistener notifies you of the time when the node is added and removed, while preferencechangelistener tells you about the value change. These events follow the process structure of the basic JavaBeans component events with the Add/removenodechangelistener (nodechangelistener) and add/removepreferencechangelistener () methods. Basically, you implement the listener first, and then register the listener, so that you will find future changes.

Author: Peter Source: forum responsible editor: Fangzhou [] provides Registry access for the java. util. prefs package added by Java 1.4

  Complete example

That's all. Listing 3 provides you with a complete example to test new features (which can also be downloaded from references ). After the program runs, it is cleared by yourself. If you want to find the value in the registry, comment out the clearing code at the end of the program.

Listing 3. Complete example

Package net. zukoski. IBM;

Import java. Io .*;
Import java. util. prefs .*;

Public class prefs {
Public static void main (string ARGs []) {
String denominations [] =
{"One", "two", "five", "Ten", "Twenty "};
String pictures [] =
{"Washington", "Jefferson", "Lincoln", "Hamilton", "Jackson "};

Nodechangelistener =
New nodechangelistener (){
Public void childadded (nodechangeevent event ){
Preferences parent = event. getparent ();
Preferences child = event. getchild ();
System. Out. println (parent. Name () + "has a new child" +
Child. Name ());
}
Public void childremoved (nodechangeevent event ){
Preferences parent = event. getparent ();
Preferences child = event. getchild ();
System. Out. println (parent. Name () + "lost a child" +
Child. Name ());
}
};

Preferencechangelistener =
New preferencechangelistener (){
Public void preferencechange (preferencechangeevent event ){
String key = event. getkey ();
String value = event. getnewvalue ();
Preferences node = event. getnode ();
System. Out. println (node. Name () + "now has a value of" +
Value + "for" + key );
}
};

// Look up User Root
Preferences prefs =
Preferences. userroot (). node ("/NET/zukoski/IBM ");

// Add listeners
Prefs. addnodechangelistener (nodechangelistener );
Prefs. addpreferencechangelistener (preferencechangelistener );

// Save a bunch of key-value pairs
For (INT I = 0, n = denominations. length; I <n; I ++ ){
Prefs. Put (denominations [I], pictures [I]);
}

// Display all the entries
Try {
String keys [] = prefs. Keys ();
For (INT I = 0, n = keys. length; I <n; I ++ ){
System. Out. println (Keys [I] + ":" + prefs. Get (Keys [I], "unknown "));
}
} Catch (backingstoreexception e ){
System. Err. println ("unable to read backing store:" + E );
}

// Create child
Preferences child = preferences. userroot (). node ("/NET/zukoski/IBM/foo ");

// Save to XML file
Try {
Fileoutputstream Fos = new fileoutputstream ("prefs. Out ");
Prefs. exportnode (FOS );
} Catch (exception e ){
System. Err. println ("unable to export nodes:" + E );
}

// Clean up
Try {
Prefs. removenode ();
} Catch (backingstoreexception e ){
System. Err. println ("unable to access backing store:" + E );
}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.