Where The Streets Have No Name

java.util.prefs.Preferences import/export예제 본문

Developement/Java

java.util.prefs.Preferences import/export예제

highheat 2009. 11. 16. 13:46

prefs.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd">
<preferences EXTERNAL_XML_VERSION="1.0">
  <root type="user">
    <map/>
    <node name="PreferenceExample">
      <map>
        <entry key="fruit" value="apple"/>
        <entry key="cost" value="1.01"/>
        <entry key="store" value="safeway"/>
      </map>
    </node>
  </root>
</preferences>
import java.util.*;
import java.util.prefs.*;
import java.io.*;

public class PreferenceExport {

    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[]) {
        PreferenceExport pe = new PreferenceExport();
        Preferences prefsRoot = Preferences.userRoot();
        Preferences myPrefs = prefsRoot.node("PreferenceExample");

        try {
            pe.setSomeProperties(myPrefs);
            myPrefs.exportSubtree(System.out);
            pe.exportToFile(myPrefs, "prefs.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.prefs.Preferences;

public class PreferenceImport {

    public static void main(String[] args) {
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream("prefs.xml"));
            Preferences.importPreferences(is);
            Preferences root = Preferences.userRoot();
            root.node("PreferenceExample").exportSubtree(System.out);
            System.out.println(root.node("PreferenceExample").get("fruit",""));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}