javaxmlpreferences

Why is Java's Preferences.exportNode() exporting non-XML characters?


I have a Java program that should save the values stored in Preference when it exits but when I use the Preferences class to export and import the stored keys/values for a node, save works but load fails with NotePad++ showing contains non-XML characters at the beginning of the file (see image).

enter image description here

Below is the minimal code. I'm pretty sure I'm just doing/missing something stupid but I can't seem to find it.

public class Test{
  java.util.prefs.Preferences userPref;
    public Test() {}
    public void run(){
            userPref = java.util.prefs.Preferences.userNodeForPackage(getClass());
            save();
            load();
    }
    public boolean save(){
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File("Test.xml");
            fileOutputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            userPref.exportNode(objectOutputStream);
            objectOutputStream.close();
            fileOutputStream.close();
            return true;    
        } catch (IOException | BackingStoreException ex) {
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException ex) {}
        }
        return false;
    }
    public boolean load(){
        try {
            File file = new File("Test.xml");
            if(!file.exists()) return false;
            Preferences.importPreferences(new FileInputStream(file)); 
            // ^ Error occurs here at the line Document doc = loadPrefsDoc(is);
        } catch (IOException ex) {
            return false;
        } catch (InvalidPreferencesFormatException ex) {
            return false;
        }
        return false;
    }
    public static void main(String args[]) {
        Test test = new Test();
        test.run();
        System.exit(0);
    }
}

Solution

  • You are writing to an ObjectOutputStream but are reading directly from a FileInputStream. Try to get rid of the ObjectOutputStream and write directly to your FileOutputStream.