Using Java Preference API with JFileChooser

Java
Following code snippet shows how to use Java Preference API with JFilechooser to make it remember last used directory location.

...
File file = new File("default.xml");
file = selectOutputFile(file);
...

private static File selectOutputFile(File outputFile) throws IOException {
        //load last selected location from preference
        Preferences prefs = Preferences.userRoot().node(MyClass.class.getName()); //or some other alias we wish to use

        JFileChooser fileChooser = new JFileChooser(prefs.get("LAST_USED_FOLDER", new File(".").getAbsolutePath()));

         //we want to filter xml files by default
        fileChooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }
                String s = f.getName();
                return s.endsWith(".xml");
            }

            @Override
            public String getDescription() {
                return "*.xml";
            }
        });

        fileChooser.setSelectedFile(outputFile); //can be omitted if required.

        int status = fileChooser.showSaveDialog(null); //or pass JFrame reference

        if (status == JFileChooser.APPROVE_OPTION) {
            outputFile = fileChooser.getSelectedFile();

            if (!outputFile.exists()) {
                outputFile.createNewFile(); //if we are going to write contents, otherwise, raise error or something
            }

            //finally save the folder of selected file in preference
            prefs.put("LAST_USED_FOLDER", outputFile.getParent());
        } else if (status == JFileChooser.CANCEL_OPTION) {
            return null;
        }

        return outputFile;
    }