Java/Development Class/Preference Properties

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

A Properties file stored in a JAR can be loaded this way

   
import java.net.URL;
import java.util.Properties;
import javax.swing.JApplet;
public class Main extends JApplet {
  public static void main(String[] a) throws Exception {
    Properties p = new Properties();
    URL url = ClassLoader.getSystemResource("/com/jexp/config/system.props");
    if (url != null)
      p.load(url.openStream());
  }
}





Convert a Properties list into a map.

   
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Main {
  public static void main(String args[]) {
    Properties prop = new Properties();
    prop.setProperty("A", "t@h.ru");
    prop.setProperty("B", "k@h.ru");
    prop.setProperty("C", "R@h.ru");
    prop.setProperty("D", "S@h.ru");
    HashMap<String, String> propMap = new HashMap<String, String>((Map) prop);
    Set<Map.Entry<String, String>> propSet;
    propSet = propMap.entrySet();
    System.out.println("Contents of map: ");
    for (Map.Entry<String, String> me : propSet) {
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }
  }
}





Determining If a Preference Node Contains a Specific Key

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  // Returns true if node contains the specified key; false otherwise.
  public static boolean contains(Preferences node, String key) {
    return node.get(key, null) != null;
  }
}





Determining If a Preference Node Contains a Specific Value

   
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
  }

  public static String containsValue(Preferences node, String value) {
    try {
      String[] keys = node.keys();
      for (int i = 0; i < keys.length; i++) {
        if (value.equals(node.get(keys[i], null))) {
          return keys[i];
        }
      }
    } catch (BackingStoreException e) {
    }
    return null;
  }
}





Determining If a Preference Node Exists

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    boolean exists = Preferences.userRoot().nodeExists("/yourValue"); // false
    Preferences.userRoot().node("/yourValue");
    exists = Preferences.userRoot().nodeExists("/yourValue"); // true
    Preferences prefs = Preferences.userRoot().node("/yourValue");
    prefs.removeNode();
    // exists = prefs.nodeExists("/yourValue");
    exists = prefs.nodeExists(""); // false
  }
}





Determining When a Preference Node Is Added or Removed

   
import java.util.prefs.NodeChangeEvent;
import java.util.prefs.NodeChangeListener;
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(String.class);
    prefs.addNodeChangeListener(new NodeChangeListener() {
      public void childAdded(NodeChangeEvent evt) {
        Preferences parent = evt.getParent();
        Preferences child = evt.getChild();
      }
      public void childRemoved(NodeChangeEvent evt) {
        Preferences parent = evt.getParent();
        Preferences child = evt.getChild();
      }
    });
    Preferences child = prefs.node("new node");
    child.removeNode();
    prefs.removeNode();
  }
}





Exporting the Preferences in a Preference Node

   
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(String.class);
    // Save some values
    prefs.put("myString", "a string"); // String
    prefs.putBoolean("myBoolean", true); // boolean
    prefs.putInt("myInt", 123); // int
    prefs.putLong("myLong", 123L); // long
    prefs.putFloat("myFloat", 12.3F); // float
    prefs.putDouble("myDouble", 12.3); // double
    byte[] bytes = new byte[10];
    prefs.putByteArray("myByteArray", bytes); // byte[]
    // Export the node to a file
    prefs.exportNode(new FileOutputStream("output.xml"));
  }
}





Exporting the Preferences in a Subtree of Preference Nodes

   

import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(String.class);
    // Save some values
    prefs.put("myString", "a string"); // String
    prefs.putBoolean("myBoolean", true); // boolean
    prefs.putInt("myInt", 123); // int
    prefs.putLong("myLong", 123L); // long
    // Save some values in the parent node
    prefs = prefs.parent();
    prefs.putFloat("myFloat", 12.3F); // float
    prefs.putDouble("myDouble", 12.3); // double
    byte[] bytes = new byte[10];
    prefs.putByteArray("myByteArray", bytes); // byte[]
    prefs.exportSubtree(new FileOutputStream("output.xml"));
  }
}





Export Preferences to XML file

    
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    FileOutputStream fos = new FileOutputStream("prefs.xml");
    myPrefs.exportSubtree(fos);
    fos.close();
  }
}





Get childrenNames from Preferences

    
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    System.out.print("Node"s children: ");
    for (String s : myPrefs.childrenNames()) {
      System.out.print(s + "");
    }

  }
}





Get keys from Preferences

    
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    System.out.print("Node"s keys: ");
    for (String s : myPrefs.keys()) {
      System.out.print(s + "");
    }
  }
}





Get name and parent from Preference

    
import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    System.out.println("Node"s name: " + myPrefs.name());
    System.out.println("Node"s parent: " + myPrefs.parent());
    System.out.println("NODE: " + myPrefs);
  }
}





Get node from Preference

    
import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    System.out.println("userNodeForPackage: "
        + Preferences.userNodeForPackage(PreferenceExample.class));
  }
}





Getting and Setting Java Type Values in a Preference

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(Main.class);
    // Preference key name
    final String PREF_NAME = "name_of_preference";
    // Save
    prefs.put(PREF_NAME, "a string"); // String
    prefs.putBoolean(PREF_NAME, true); // boolean
    prefs.putInt(PREF_NAME, 123); // int
    prefs.putLong(PREF_NAME, 123L); // long
    prefs.putFloat(PREF_NAME, 12.3F); // float
    prefs.putDouble(PREF_NAME, 12.3); // double
    byte[] bytes = new byte[1024];
    prefs.putByteArray(PREF_NAME, bytes); // byte[]
    // Retrieve
    String s = prefs.get(PREF_NAME, "a string"); // String
    boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
    int i = prefs.getInt(PREF_NAME, 123); // int
    long l = prefs.getLong(PREF_NAME, 123L); // long
    float f = prefs.getFloat(PREF_NAME, 12.3F); // float
    double d = prefs.getDouble(PREF_NAME, 12.3); // double
    bytes = prefs.getByteArray(PREF_NAME, bytes); // byte[]
  }
}





Getting and Setting Properties

   
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
  public static void main(String[] argv) throws Exception {
    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream("filename.properties"));
    } catch (IOException e) {
    }
    String string = properties.getProperty("a.b");
    properties.setProperty("a.b", "new value");
  }
}





Getting the Maximum Size of a Preference Key and Value

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Get maximum key length
    int keyMax = Preferences.MAX_KEY_LENGTH;
    // Get maximum value length
    int valueMax = Preferences.MAX_VALUE_LENGTH;
    // Get maximum length of byte array values
    int bytesMax = Preferences.MAX_VALUE_LENGTH * 3 / 4;
  }
}





Getting the Roots of the Preference Trees

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Get the system root
    Preferences prefs = Preferences.systemRoot();
    // Get the user root
    prefs = Preferences.userRoot();
    // The name of a root is ""
    String name = prefs.name();
    // The parent of a root is null
    Preferences parent = prefs.parent();
    // The absolute path of a root is "/"
    String path = prefs.absolutePath();
  }
}





Get value from Preferences

    

import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    for (String s : myPrefs.keys()) {
      System.out.println("" + s + "= " + myPrefs.get(s, ""));
    }
  }
}





Have a multi-line value in a properties file

   
// add a slash \ to continue the value on the next line.
prop1=line1\
line2\
line3
import java.net.URL;
import java.util.Properties;
public class Main {
  public static void main(String args[]) throws Exception {
    Properties props = new Properties();
    URL url = ClassLoader.getSystemResource("props.properties");
    props.load(url.openStream());
    System.out.println("prop1 :\n " + props.get("prop1"));
    System.out.println("prop2 :\n " + props.get("prop2"));
  }
}





Here is an example of the contents of a properties file:

   
    # a comment
    ! a comment
    
    key1 = a string
    key2 = a string with escape sequences \t \n \r \\ \" \" \ (space) \u0123
    key3 = a string with a continuation line \
        continuation line
    com.jexp.ui = another string





Listening for Changes to Preference Values in a Preference Node

   
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(String.class);
    prefs.addPreferenceChangeListener(new PreferenceChangeListener() {
      public void preferenceChange(PreferenceChangeEvent evt) {
        Preferences node = evt.getNode();
        String key = evt.getKey();
        String newValue = evt.getNewValue();
      }
    });
    prefs.put("key", "a string");
    prefs.put("key", "a new string");
    prefs.remove("key");
  }
}





Listing All System Properties

   
import java.util.Enumeration;
import java.util.Properties;
public class Main {
  public static void main(String[] argv) throws Exception {
    Properties props = System.getProperties();
    Enumeration e = props.propertyNames();
    for (; e.hasMoreElements();) {
      String propName = (String) e.nextElement();
      System.out.println(propName );
      String propValue = (String) props.get(propName);
      System.out.println(propValue);
    }
  }
}





Listing the system properties

   
import java.util.Enumeration;
import java.util.Properties;
public class Main {
  public static void main(String[] args) {
    Properties prop = System.getProperties();
    Enumeration enumeration = prop.keys();
    while (enumeration.hasMoreElements()) {
      String key = (String) enumeration.nextElement();
      System.out.println(key + " = " + prop.getProperty(key));
    }
  }
}





Load a properties file in the classpath

   
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Properties;
public class Main {
  public static void main(String args[]) throws Exception {
    
    Properties props = new Properties();
    URL url = ClassLoader.getSystemResource("myprops.props");
    props.load(url.openStream());
    System.out.println(props);
  }
}





Load a properties file in the startup directory

   
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class Main {
  public static void main(String args[]) throws Exception {
    Properties props = new Properties();
    props = new java.util.Properties();
    String path = new Main().getClass().getProtectionDomain().getCodeSource().getLocation()
        .toString().substring(6);
    FileInputStream fis = new FileInputStream(new File(path + "\\myprops.props"));
    props.load(fis);
    System.out.println(props);
  }
}





Loading configuration parameters from text file based properties

   
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;
public class Main {
  public static void main(String[] args) throws Exception {
    Properties config = new Properties();
    config.load(new FileInputStream("conf-file.pros"));
    Enumeration en = config.keys();
    while (en.hasMoreElements()) {
      String key = (String) en.nextElement();
      System.out.println(key + ":" + config.get(key));
    }
  }
}





Load properties from XML file

   
/*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.ru/dtd/properties.dtd">
<properties>
  <comment>Application Configuration</comment>
  <entry key="data.folder">D:\Data</entry>
  <entry key="jdbc.url">jdbc:mysql://localhost/mydb</entry>
</properties>
*/
import java.io.FileInputStream;
import java.util.Properties;
public class Main {
  public static void main(String[] args) {
    Properties properties = new Properties();
    String dataFolder = properties.getProperty("data.folder");
    System.out.println("dataFolder = " + dataFolder);
    String jdbcUrl = properties.getProperty("jdbc.url");
    System.out.println("jdbcUrl = " + jdbcUrl);
  }
  public Properties readProperties() throws Exception {
    Properties properties = new Properties();
    FileInputStream fis = new FileInputStream("configuration.xml");
    properties.loadFromXML(fis);
    return properties;
  }
}





Parse Properties Files

   
/*
  Java, XML, and Web Services Bible
  Mike Jasnowski
  ISBN: 0-7645-4847-6
*/
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.Properties;
import java.util.Enumeration;
import org.apache.xerces.parsers.*;
public class ParseNonXML extends DefaultHandler{
       public static void main(String args[]) throws SAXException{
       
              PropertyFileParser pfp = new PropertyFileParser();
              pfp.setContentHandler(new ParseNonXML());
              pfp.parse(buildProperties());
       }
       
       public static Properties buildProperties(){
              Properties props = new Properties();
              for (int i=0;i<10;i++)
                   props.setProperty("key"+i,"value"+i);
              return props;
       }
       
       public void startDocument(){System.out.println("<keys>");}
       public void endDocument(){System.out.println("</keys>");}
       public void characters(char[] data,int start,int end){
              String str = new String(data,start,end);
              System.out.print(str);
       }
       public void startElement(String uri,String qName,String lName,Attributes atts){
              System.out.print("<"+lName+">");
       }
       public void endElement(String uri,String qName,String lName){
              System.out.println("</"+lName+">");
       }
}
class PropertyFileParser extends SAXParser{
       private Properties props = null;
       private ContentHandler handler = null;
       public void parse(Properties props) throws SAXException{
              handler = getContentHandler();
              handler.startDocument();
              Enumeration e = props.propertyNames();
              while (e.hasMoreElements()){
                     String key = (String)e.nextElement();
                     String val = (String)props.getProperty(key);
                     handler.startElement("",key,key,new AttributesImpl());
                     char[] chars = getChars(val);
                     handler.characters(chars,0,chars.length);
                     handler.endElement("",key,key);                     
              }
              handler.endDocument();
       }     
       private char[] getChars(String value){
               char[] chars = new char[value.length()];
               value.getChars(0,value.length(),chars,0);
               return chars;
       }
       
}





Passing references around

   
// : appendixa:PassReferences.java
// Passing references around.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class PassReferences {
  public static void f(PassReferences h) {
    System.out.println("h inside f(): " + h);
  }
  public static void main(String[] args) {
    PassReferences p = new PassReferences();
    System.out.println("p inside main(): " + p);
    f(p);
  }
} ///:~





Preference Example:: export To File

   
import java.util.*;
import java.util.prefs.*;
import java.io.*;
public class PreferenceExample {
public void printInformation(Preferences p) throws BackingStoreException{
        System.out.println("Node"s absolute path: " + p.absolutePath());
        System.out.print("Node"s children: ");
        for(String s : p.childrenNames()) {
            System.out.print(s + " ");
        }
        System.out.println("");
        System.out.print("Node"s keys: ");
        for(String s : p.keys()) {
            System.out.print(s + " ");
        }
        System.out.println("");
        System.out.println("Node"s name: " + p.name());
        System.out.println("Node"s parent: " + p.parent());
        System.out.println("NODE: " + p);
        System.out.println("userNodeForPackage: " +
                Preferences.userNodeForPackage(PreferenceExample.class));
        System.out.println("All information in node");
        for(String s : p.keys()) {
            System.out.println("  " + s + " = " + p.get(s, ""));
        }
    }
  public void setSomeProperties(Preferences p) throws BackingStoreException {
    p.put("fruit", "apple");
    p.put("cost", "1.01");
    p.put("store", "safeway");
  }
  public void exportToFile(Preferences p, String fileName)
      throws BackingStoreException {
    try {
      FileOutputStream fos = new FileOutputStream(fileName);
      p.exportSubtree(fos);
      fos.close();
    } catch (IOException ioe) {
      System.out.println("IOException in exportToFile\n" + ioe);
      ioe.printStackTrace();
    }
  }
  public static void main(String args[]) {
    PreferenceExample pe = new PreferenceExample();
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    try {
      pe.setSomeProperties(myPrefs);
      pe.printInformation(myPrefs);
      pe.exportToFile(myPrefs, "prefs.xml");
    } catch (BackingStoreException bse) {
      System.out.println("Problem with accessing the backing store\n"
          + bse);
      bse.printStackTrace();
    }
  }
}





Preferences Demo

   
// : c12:PreferencesDemo.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.Arrays;
import java.util.Iterator;
import java.util.prefs.Preferences;
public class PreferencesDemo {
  public static void main(String[] args) throws Exception {
    Preferences prefs = Preferences
        .userNodeForPackage(PreferencesDemo.class);
    prefs.put("Location", "Oz");
    prefs.put("Footwear", "Ruby Slippers");
    prefs.putInt("Companions", 4);
    prefs.putBoolean("Are there witches?", true);
    int usageCount = prefs.getInt("UsageCount", 0);
    usageCount++;
    prefs.putInt("UsageCount", usageCount);
    Iterator it = Arrays.asList(prefs.keys()).iterator();
    while (it.hasNext()) {
      String key = it.next().toString();
      System.out.println(key + ": " + prefs.get(key, null));
    }
    // You must always provide a default value:
    System.out.println("How many companions does Dorothy have? "
        + prefs.getInt("Companions", 0));
  }
} ///:~





Properties Demo

   
/* From http://java.sun.ru/docs/books/tutorial/index.html */

/*
 * Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
import java.util.*;
public class PropertiesDemo {
   static void displayValue(Locale currentLocale, String key) {
      ResourceBundle labels = 
         ResourceBundle.getBundle("LabelsBundle",currentLocale);
      String value  = labels.getString(key);
      System.out.println(
           "Locale = " + currentLocale.toString() + ", " +
           "key = " + key + ", " +
           "value = " + value);
   } // displayValue

   static void iterateKeys(Locale currentLocale) {
      ResourceBundle labels = 
         ResourceBundle.getBundle("LabelsBundle",currentLocale);
      Enumeration bundleKeys = labels.getKeys();
      while (bundleKeys.hasMoreElements()) {
         String key = (String)bundleKeys.nextElement();
         String value  = labels.getString(key);
         System.out.println("key = " + key + ", " +
           "value = " + value);
      }
   } // iterateKeys

   static public void main(String[] args) {
      Locale[] supportedLocales = {
         Locale.FRENCH,
         Locale.GERMAN,
         Locale.ENGLISH
      };
      for (int i = 0; i < supportedLocales.length; i ++) {
          displayValue(supportedLocales[i], "s2");
      }
      System.out.println();
      iterateKeys(supportedLocales[0]);
   } // main
} // class
//File:LabelsBundle_de_DE.properties
/*
# This is the LabelsBundle_de_DE.properties file.
s1 = Computer
s2 = Platte
s3 = Monitor
s4 = Tastatur
*/
//File: LabelsBundle_fr.properties
/*
# This is the LabelsBundle_fr.properties file.
s1 = Ordinateur
s2 = Disque dur
s3 = Moniteur
s4 = Clavier
*/
//File: LabelsBundle.properties
/*
# This is the default LabelsBundle.properties file
s1 = computer
s2 = disk
s3 = monitor
s4 = keyboard
*/





Properties load

   
import java.util.*;
import java.io.*;
public class Load {
  public static void main (String args[]) throws Exception {
    Properties p = new Properties();
    p.load(new FileInputStream("colon.txt"));
    p.list(System.out);
  }
}
//File: colon.txt
/*
foo:bar
one
two
three=four
five  six seven eight
nine ten

*/





Properties Test

   
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

import java.io.FileInputStream;
import java.util.Properties;
public class PropertiesTest {
  public static void main(String[] args) throws Exception {
    // set up new properties object
    // from file "myProperties.txt"
    FileInputStream propFile = new FileInputStream("myProperties.txt");
    Properties p = new Properties(System.getProperties());
    p.load(propFile);
    // set the system properties
    System.setProperties(p);
    // display new properties
    System.getProperties().list(System.out);
  }
}
//file:myProperties.txt
/*
subliminal.message=Buy Java Now!

*/





Properties TreeMap and Stream

   
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
public class List {
  public static void main(String args[]) throws Exception {
    Properties p = System.getProperties();
    p.list(System.out);
    FileOutputStream fos = new FileOutputStream("sys.out");
    p.store(fos, null);
    fos.close();
    Map map = new TreeMap(p);
    System.out.println(map);
  }
}





PropsToXML takes a standard Java properties file, and converts it into an XML file

   

/*--
 Copyright (C) 2001 Brett McLaughlin.
 All rights reserved.
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions, and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions, and the disclaimer that follows
    these conditions in the do*****entation and/or other materials
    provided with the distribution.
 3. The name "Java and XML" must not be used to endorse or promote products
    derived from this software without prior written permission.  For
    written permission, please contact brett@newInstance.ru.
 In addition, we request (but do not require) that you include in the
 end-user do*****entation provided with the redistribution and/or in the
 software itself an acknowledgement equivalent to the following:
     "This product includes software developed for the
      "Java and XML" book, by Brett McLaughlin (O"Reilly & Associates)."
 THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED.  IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.
 */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.jdom.Do*****ent;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
/**
 * <b><code>PropsToXML</code></b> takes a standard Java properties
 *   file, and converts it into an XML format. This makes properties
 *   like <code>enhydra.classpath.separator</code> "groupbable" by
 *   "enhydra", "classpath", and by the key name, "separator", which
 *   the standard Java <code>java.util.Properties</code> class does
 *   not allow.
 */
public class Main {
    /**
     * <p> This will take the supplied properties file, and
     *   convert that file to an XML representation, which is
     *   then output to the supplied XML do*****ent filename. </p>
     *
     * @param propertiesFilename file to read in as Java properties.
     * @param xmlFilename file to output XML representation to.
     * @throws <code>IOException</code> - when errors occur.
     */
    public void convert(String propertiesFilename, String xmlFilename)
        throws IOException {
        // Get Java Properties object
        FileInputStream input = new FileInputStream(propertiesFilename);
        Properties props = new Properties();
        props.load(input);
        // Convert to XML
        convertToXML(props, xmlFilename);
    }
    /**
     * <p> This will handle the detail of conversion from a Java
     *  <code>Properties</code> object to an XML do*****ent. </p>
     *
     * @param props <code>Properties</code> object to use as input.
     * @param xmlFilename file to output XML to.
     * @throws <code>IOException</code> - when errors occur.
     */
    private void convertToXML(Properties props, String xmlFilename)
        throws IOException {
        // Create a new JDOM Do*****ent with a root element "properties"
        Element root = new Element("properties");
        Do*****ent doc = new Do*****ent(root);
        // Get the property names
        Enumeration propertyNames = props.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String)propertyNames.nextElement();
            String propertyValue = props.getProperty(propertyName);
            createXMLRepresentation(root, propertyName, propertyValue);
        }
        // Output do*****ent to supplied filename
        XMLOutputter outputter = new XMLOutputter("  ", true);
        FileOutputStream output = new FileOutputStream(xmlFilename);
        outputter.output(doc, output);
    }
    /**
     * <p> This will convert a single property and its value to
     *  an XML element and textual value. </p>
     *
     * @param root JDOM root <code>Element</code> to add children to.
     * @param propertyName name to base element creation on.
     * @param propertyValue value to use for property.
     */
    private void createXMLRepresentation(Element root,
                                         String propertyName,
                                         String propertyValue) {
        /*
        Element element = new Element(propertyName);
        element.setText(propertyValue);
        root.addContent(element);
        */
        int split;
        String name = propertyName;
        Element current = root;
        Element test = null;
        while ((split = name.indexOf(".")) != -1) {
            String subName = name.substring(0, split);
            name = name.substring(split+1);
            // Check for existing element
            if ((test = current.getChild(subName)) == null) {
                Element subElement = new Element(subName);
                current.addContent(subElement);
                current = subElement;
            } else {
                current = test;
            }
        }
        // When out of loop, what"s left is the final element"s name
        Element last = new Element(name);
        // last.setText(propertyValue);
        last.setAttribute("value", propertyValue);
        current.addContent(last);
    }
    /**
     * <p> Provide a static entry point for running. </p>
     */
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java javaxml2.PropsToXML " +
                "[properties file] [XML file for output]");
            System.exit(0);
        }
        try {
            PropsToXML propsToXML = new PropsToXML();
            propsToXML.convert(args[0], args[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*   Java and XML, Second Edition
 *   Solutions to Real-World Problems
 *   By Brett McLaughlin
 *   Second Edition August 2001
 *   ISBN: 0-596-00197-5
 *   http://www.oreilly.ru/catalog/javaxml2/
 */





Put key value pair to Preference

    
import java.io.FileOutputStream;
import java.util.prefs.Preferences;
public class PreferenceExample {
  public static void main(String args[]) throws Exception {
    Preferences prefsRoot = Preferences.userRoot();
    Preferences myPrefs = prefsRoot.node("PreferenceExample");
    myPrefs.put("A", "a");
    myPrefs.put("B", "b");
    myPrefs.put("C", "c");
    System.out.println("Node"s absolute path: " + myPrefs.absolutePath());
  }
}





Read a configuration file using java.util.Properties

   
app.config file:
app.name=Properties Sample Code
app.version=1.0

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class Main {
  public static void main(String[] args) throws Exception {
    Properties prop = new Properties();
    String fileName = "app.config";
    InputStream is = new FileInputStream(fileName);
    prop.load(is);
    System.out.println(prop.getProperty("app.name"));
    System.out.println(prop.getProperty("app.version"));
    System.out.println(prop.getProperty("app.vendor", "Java"));
  }
}





Reading and Writing a Properties File

   
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Read properties file.
    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream("filename.properties"));
    } catch (IOException e) {
    }
    // Write properties file.
    try {
      properties.store(new FileOutputStream("filename.properties"), null);
    } catch (IOException e) {
    }
  }
}





Read system property as an integer

   
 
public class Main {
  public static void main(String[] args) {
    System.setProperty("app.major.version", "1");
    System.setProperty("app.minor.version", "19");
    Integer major = Integer.getInteger("app.major.version");
    Integer minor = Integer.getInteger("app.minor.version");
    System.out.println("App version = " + major + "." + minor);
  }
}





Read / write data in Windows registry

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] args) {
    String PREF_KEY = "org.username";
    // Write Preferences information to HKCU (HKEY_CURRENT_USER),HKCU\Software\JavaSoft\Prefs\
    Preferences userPref = Preferences.userRoot();
    userPref.put(PREF_KEY, "a");
    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\
    Preferences systemPref = Preferences.systemRoot();
    systemPref.put(PREF_KEY, "b");
    System.out.println("Preferences = " + systemPref.get(PREF_KEY, PREF_KEY + " was not found."));
  }
}





Removing a Preference from a Preference Node

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    // Get the user preference node for java.lang
    Preferences prefs = Preferences.userNodeForPackage(String.class);
    // Remove a preference in the node
    final String PREF_NAME = "name_of_preference";
    prefs.remove(PREF_NAME);
    // Remove all preferences in the node
    prefs.clear();
  }
}





Removing a Preference Node

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    boolean exists = Preferences.userRoot().nodeExists("/yourValue"); // false
    if (!exists) {
      Preferences prefs = Preferences.userRoot().node("/yourValue");
      prefs.removeNode();
      // prefs.removeNode();
    }
    Preferences prefs = Preferences.userRoot().node("/yourValue/child");
    exists = Preferences.userRoot().nodeExists("/yourValue"); // true
    exists = Preferences.userRoot().nodeExists("/yourValue/child"); // true
    Preferences.userRoot().node("/yourValue").removeNode();
    exists = Preferences.userRoot().nodeExists("/yourValue"); // false
    exists = Preferences.userRoot().nodeExists("/yourValue/child"); // false
  }
}





Retrieve the preference node using a Class object and saves and retrieves a preference in the node.

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(Main.class);
    final String PREF_NAME = "your_preference";
    String newValue = "a string";
    prefs.put(PREF_NAME, newValue);
    String defaultValue = "default string";
    String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"
  }
}





Retrieving a Preference Node

   

import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    // System preference nodes
    // Use a Class
    Preferences prefs = Preferences.systemNodeForPackage(java.lang.String.class);
    // Use an absolute path
    prefs = Preferences.systemRoot().node("/java/lang/String");
    // Use a relative path
    prefs = Preferences.systemRoot().node("/javax/swing");
    prefs = prefs.node("text/html");
    // User preference nodes
    // Use a class
    prefs = Preferences.userNodeForPackage(Main.class);
    // Use an absolute path
    prefs = Preferences.userRoot().node("/com/mycompany");
    // Use a relative path
    prefs = Preferences.userRoot().node("/javax/swing");
    prefs = prefs.node("text/html");
  }
}





Retrieving the Parent and Child Nodes of a Preference Node

   
import java.util.prefs.Preferences;
public class Main {
  public static void main(String[] argv) throws Exception {
    Preferences prefs = Preferences.userNodeForPackage(java.lang.String.class);
    Preferences node = prefs.parent(); // /java
    node = node.parent(); // null
    String[] names = null;
    names = prefs.childrenNames();
    for (int i = 0; i < names.length; i++) {
      node = prefs.node(names[i]);
    }
  }
}





Saving Data with the Preferences API

   
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class PlanetPrefs {
  public static void main(String args[]) {
    String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter",
        "Saturn", "Uranus", "Neptune", "Pluto" };
    int moons[] = { 0, 0, 1, 2, 16, 18, 21, 8, 1 };
    Preferences prefs = Preferences.userRoot()
        .node("/MasteringJava/Chap17");
    for (int i = 0, n = names.length; i < n; i++) {
      prefs.putInt(names[i], moons[i]);
    }
    try {
      String keys[] = prefs.keys();
      for (int i = 0, n = keys.length; i < n; i++) {
        System.out.println(keys[i] + ": " + prefs.getInt(keys[i], 0));
      }
    } catch (BackingStoreException e) {
      System.err.println("Unable to read backing store: " + e);
    }
  }
}





Sort Properties when saving

   
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
public class Main{
  public static void main(String[] args) throws Exception {
    SortedProperties sp = new SortedProperties();
    sp.put("B", "value B");
    sp.put("C", "value C");
    sp.put("A", "value A");
    sp.put("D", "value D");
    FileOutputStream fos = new FileOutputStream("sp.props");
    sp.store(fos, "sorted props");
  }
}
class SortedProperties extends Properties {
  public Enumeration keys() {
     Enumeration keysEnum = super.keys();
     Vector<String> keyList = new Vector<String>();
     while(keysEnum.hasMoreElements()){
       keyList.add((String)keysEnum.nextElement());
     }
     Collections.sort(keyList);
     return keyList.elements();
  }
  
}





Static methods for retrieving and system properties and converting them to various types

  
/*
 * Copyright 2006 (C) TJDO.
 * All rights reserved.
 *
 * This software is distributed under the terms of the TJDO License version 1.0.
 * See the terms of the TJDO License in the documentation provided with this software.
 *
 * $Id: SystemProperty.java,v 1.1 2006/10/11 23:37:23 jackknifebarber Exp $
 */

/**
 * Static methods for retrieving and system properties and converting them to
 * various types.
 * <p>
 * These methods are very similar to others in <tt>java.lang</tt>; for example,
 * {@link #intValue} is nearly the same as <tt>Integer.getInteger(String,int)</tt>.
 * The main difference is that these methods log warnings for invalid property
 * values.
 *
 * @author 
 * @version $Revision: 1.1 $
 */
public final class SystemProperty
{

    /** Private constructor prevents instantiation. */
    private SystemProperty()
    {
    }
    /**
     * Returns the value of a system property as a boolean.
     * If such a system property exists it is converted to a boolean with
     * <tt>Boolean.valueOf(String)</tt>.
     * Returns the specified default value if no such system property exists or
     * the property value is invalid.
     *
     * @return
     *      the boolean value of the specified property
     */
    public static boolean booleanValue(String propName, boolean defaultValue)
    {
        String prop = System.getProperty(propName);
        boolean val;
        if (prop == null)
            val = defaultValue;
        else
            val = Boolean.valueOf(prop.trim()).booleanValue();

        return val;
    }
    /**
     * Returns the value of a system property as an integer.
     * If such a system property exists it is converted to an integer with
     * <tt>Integer.decode(String)</tt>.
     * Returns the specified default value if no such system property exists or
     * the property value is invalid.
     *
     * @return
     *      the integer value of the specified property
     */
    public static int intValue(String propName, int defaultValue)
    {
        String prop = System.getProperty(propName);
        int val;
        if (prop == null)
            val = defaultValue;
        else
        {
            try
            {
                val = Integer.decode(prop.trim()).intValue();
            }
            catch (NumberFormatException e)
            {
               
                val = defaultValue;
            }
        }

        return val;
    }
    /**
     * Returns the value of a system property as a String.
     * Returns the specified default value if no such system property exists.
     *
     * @return
     *      the String value of the specified property
     */
    public static String stringValue(String propName, String defaultValue)
    {
        String val = System.getProperty(propName);
        if (val == null)
            val = defaultValue;

        return val;
    }
}





Store properties as XML file

   
import java.io.FileOutputStream;
import java.util.Properties;
public class Main {
  public static void main(String[] args) throws Exception {
    Properties properties = new Properties();
    properties.setProperty("database.type", "mysql");
    properties.setProperty("database.url", "jdbc:mysql://localhost/mydb");
    properties.setProperty("database.username", "root");
    properties.setProperty("database.password", "root");
    FileOutputStream fos = new FileOutputStream("database-configuration.xml");
    properties.storeToXML(fos, "Database Configuration", "UTF-8");
  }
}
 
 
The saved XML file will look like the properties file below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.ru/dtd/properties.dtd">
  <properties>
    <comment>Database Configuration</comment>
    <entry key="database.password">root</entry>
    <entry key="database.url">jdbc:mysql://localhost/mydb</entry>
    <entry key="database.type">mysql</entry>
    <entry key="database.username">root</entry>
  </properties





Store recent items (e.g. recent file in a menu or recent search text in a search dialog)

  
/*
 * jMemorize - Learning made easy (and fun) - A Leitner flashcards tool
 * Copyright(C) 2004-2006 Riad Djemili
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 1, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
/**
 * A simple data structure to store recent items (e.g. recent file in a menu or
 * recent search text in a search dialog).
 * 
 * @author djemili
 */
public class RecentItems
{
    public interface RecentItemsObserver
    {
        void onRecentItemChange(RecentItems src);
    }
    
    public final static String RECENT_ITEM_STRING = "recent.item."; //$NON-NLS-1$
    
    private int                       m_maxItems;
    private Preferences               m_prefNode;
    private List<String>              m_items            = new ArrayList<String>();
    private List<RecentItemsObserver> m_observers        = new ArrayList<RecentItemsObserver>();
    
    public RecentItems(int maxItems, Preferences prefNode)
    {
        m_maxItems = maxItems;
        m_prefNode = prefNode;
        
        loadFromPreferences();
    }
    
    public void push(String item)
    {
        m_items.remove(item);
        m_items.add(0, item);
        
        if (m_items.size() > m_maxItems)
        {
            m_items.remove(m_items.size() - 1);
        }
        
        update();
    }
    
    public void remove(Object item)
    {
        m_items.remove(item);
        update();
    }
    
    public String get(int index)
    {
        return (String)m_items.get(index);
    }
    
    public List<String> getItems()
    {
        return m_items;
    }
    
    public int size()
    {
        return m_items.size();
    }
    
    public void addObserver(RecentItemsObserver observer)
    {
        m_observers.add(observer);
    }
    
    public void removeObserver(RecentItemsObserver observer)
    {
        m_observers.remove(observer);
    }
    
    private void update()
    {
        for (RecentItemsObserver observer : m_observers)
        {
            observer.onRecentItemChange(this);
        }
        
        storeToPreferences();
    }
    
    private void loadFromPreferences()
    {
        // load recent files from properties
        for (int i = 0; i < m_maxItems; i++)
        {
            String val = m_prefNode.get(RECENT_ITEM_STRING+i, ""); //$NON-NLS-1$
            if (!val.equals("")) //$NON-NLS-1$
            {
                m_items.add(val);
            }
            else
            {
                break;
            }
        }
    }
    
    private void storeToPreferences()
    {
        for (int i = 0; i < m_maxItems; i++)
        {
            if (i < m_items.size())
            {
                m_prefNode.put(RECENT_ITEM_STRING+i, (String)m_items.get(i));
            }
            else
            {
                m_prefNode.remove(RECENT_ITEM_STRING+i);
            }
        }
    }
}





Storing/loading Preferences

  
/*
 * jMemorize - Learning made easy (and fun) - A Leitner flashcards tool
 * Copyright(C) 2004-2006 Riad Djemili
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 1, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
import java.util.prefs.Preferences;
/**
 * Just some helper methods for storing/loading Preferences.
 * 
 * @author djemili
 */
public class PreferencesTool
{
    public static void putIntArray(Preferences node, String key, int[] ints)
    {
        StringBuffer buffer = new StringBuffer();
        int index = 0;
        
        while (index < ints.length - 1)
        {
            buffer.append(ints[index++]);
            buffer.append(",");
        }
        buffer.append(ints[index]);
        
        node.put(key, buffer.toString());
    }
    
    public static int[] getIntArray(Preferences node, String key) //TODO add fallbackvalue
    {
        String intArrayString = node.get(key, null);
        if (intArrayString == null)
        {
            return null;
        }
        
        String[] strings = intArrayString.split(","); //$NON-NLS-1$
        int[] ints = new int[strings.length];
        for (int i = 0; i < strings.length; i++)
        {
            ints[i] = Integer.parseInt(strings[i]);
        }
        
        return ints;
    }
}





To read a Properties file via an Applet

   

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import javax.swing.JApplet;
public class Main extends JApplet{
  public void init(){
    Properties p = new Properties();
    try {
      p.load((new URL(getCodeBase(), "user.props")).openStream());
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}





Use the Registry to store informations (Preferences API)

   
import java.util.prefs.Preferences;
public class Main {
  public static final String REALKEY = "com.jexp.gui";
  public static void main(String[] args) {
    Preferences p = Preferences.userRoot();
    p.put(REALKEY, "bar");
    System.out.println(p);
    System.out.println(p.get(REALKEY, "key"));
    p = Preferences.systemRoot();
    p.put(REALKEY, "key 2");
    System.out.println(p);
    System.out.println(p.get(REALKEY, "default"));
  }
}





Use XML with Properties

   
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Properties;
public class Main {
  public static void main(String args[]) throws Exception {
    Properties p = new Properties();
    p.put("today", new Date().toString());
    p.put("user", "A");
    FileOutputStream out = new FileOutputStream("user.props");
    p.storeToXML(out, "updated");
    FileInputStream in = new FileInputStream("user.props");
    p.loadFromXML(in);
    p.list(System.out);
  }
}
/*
The XML looks like
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.ru/dtd/properties.dtd">
<properties>
    <comment>your wordings</comment>
    <entry key="user">A</entry>
    <entry key="today">12/12/2009</entry>
</properties>
*/





Utility class for preferences

  
/*
 * Copyright Javelin Software, All rights reserved.
 */

import java.util.*;
import java.util.prefs.*;

/**
 * Utility class for prefs
 *
 * @author Robin Sharp
 */
public class PrefsUtil 
{   
    /**
     * Clear all the node
     */
    public static void clear( Preferences preferences, String key )
    {
        try
        {
            if( preferences.nodeExists( key ) )
            {
                preferences.node( key ).clear();
            }
        }
        catch( BackingStoreException bse )
        {
            bse.printStackTrace();
        }
    }
    /**
     * Remove the node
     */
    public static void remove( Preferences preferences, String key )
    {
        try
        {
            if( preferences.nodeExists( key ) )
            {
                preferences.node( key ).removeNode();
            }
        }
        catch( BackingStoreException bse )
        {
            bse.printStackTrace();
        }
    }
    
    /**
     * Puts a list into the preferences.
     */
    public static void putMap( Preferences preferences, Map map, String key )
    {
        putMap( preferences.node( key ), map );
    }
    
    /**
     * Puts a list into the preferences.
     */
    public static void putMap( Preferences preferences, Map map )
    {
        if( preferences == null )
        {
            throw new IllegalArgumentException( "Preferences not set." );
        }
    
        for( Iterator iter = map.entrySet().iterator(); iter.hasNext(); )
        {
            Map.Entry entry = (Map.Entry)iter.next();
            Object value = entry.getValue();
            preferences.put( entry.getKey().toString(), value == null ? null : value.toString() );
        }
    }
       
    /**
     * Gets a Map from the preferences.
     */
    public static Map getMap( Preferences preferences, String key )
    {
        return getMap( preferences.node( key ) );
    }
    
    /**
     * Gets a Map from the preferences.
     */
    public static Map getMap( Preferences preferences )
    {
        if( preferences == null )
        {
            throw new IllegalArgumentException( "Preferences not set." );
        }
        Map map = new HashMap();
        
        try
        {
            String[] keys = preferences.keys();
            for( int index = 0; index < keys.length; index++ )
            {
                map.put( keys[index], preferences.get( keys[index], null ) );
            }
        }
        catch( BackingStoreException bse )
        {
            bse.printStackTrace();
        }
        
       return map;
    }
    
    /**
     * Puts a list into the preferences starting with "0" then "1"
     */
    public static void putList( Preferences preferences, List list, String key )
    {
        putList( preferences.node( key ), list );
    }
    
    /**
     * Puts a list into the preferences starting with "0" then "1"
     */
    public static void putList( Preferences preferences, List list )
    {
        if( preferences == null )
        {
            throw new IllegalArgumentException( "Preferences not set." );
        }
        //System.out.println( "LIST=" + list );
        for( int index = 0; list != null && index < list.size(); index++ )
        {
            Object value = list.get( index );
            preferences.put( ""+index, value == null ? null : value.toString() );
        }
    }
    /**
     * Gets a List from the preferences, starting with "0", then "1" etc
     */
    public static List getList( Preferences preferences, String key )
    {
        return getList( preferences.node( key ) );
    }
    
    /**
     * Gets a List from the preferences, starting with "0", then "1" etc
     */
    public static List getList( Preferences preferences )
    {
        if( preferences == null )
        {
            throw new IllegalArgumentException( "Preferences not set." );
        }
        List list = new ArrayList();
    
        for( int index = 0; index < 1000; index++ )
        {
            String value = preferences.get( ""+index, null );
            if( value == null ) break;
            //System.out.println( ""+index+ " " + value );
            list.add( value );
        }
        return list;
    }
    
    public static void main( String[] args )
    {
        try
        {
            Map map = new HashMap();
            map.put( "0", "A" );
            map.put( "1", "B" );
            map.put( "2", "C" );
            map.put( "3", "D" );
            map.put( "5", "f" );
            Preferences prefs = Preferences.userNodeForPackage( String.class );
            
            String RECENT_FILES = "XXX";
            
        List recentFiles = PrefsUtil.getList( prefs, RECENT_FILES );
        PrefsUtil.clear( prefs, RECENT_FILES );
     
        PrefsUtil.putList( prefs, recentFiles, RECENT_FILES );
        //System.out.println( PrefsUtil.getList( prefs, RECENT_FILES ) );
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
    }
}