SaintLike SaintLike - 4 months ago 24x
Java Question

Set default saving extention with JFileChooser

I'm trying to save a file using

. However, I seem to be having some trouble with it. Here's my code:

if (e.getSource() == saveMenu) {

JFileChooser chooser = new JFileChooser();

FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
// add filters

int result = chooser.showSaveDialog(Simulation.this);

if (result == chooser.APPROVE_OPTION) {


This doesn't force the file to have a
extension, so I've tryed to use the following code to force the file to be saved with the extention .xml

OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = null;
try {
xmlWriter = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(f+".xml"), "UTF8"),

However, with this I can't prevent the user from writing
in the
and if they do that, the file will have "two extentions": it will be a file named

So my questions are:

  • How can I make the
    save an xml file by default?

  • If the user inserts a file name like xpto.xml, how can I save it as xpto.xml and not xpto.xml.xml?


As you've noticed, JFileChooser doesn't enforce the FileFilter on a save. It will grey-out the existing non-XML file in the dialog it displays, but that's it. To enforce the filename, you have to do all the work. (This isn't just a matter of JFileChooser sucking -- it's a complex problem to deal with. Your might want your users to be able to name their files xml.xml.xml.xml.)

In your case, I recommend using FilenameUtils from Commons IO:

File file = chooser.getSelectedFile();
if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("xml")) {
    // filename is OK as-is
} else {
    file = new File(file.toString() + ".xml");  // append .xml if "foo.jpg.xml" is OK
    file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".xml"); // ALTERNATIVELY: remove the extension (if any) and replace it with ".xml"

There's also some ideas for what to do if you want multiple types in the save dialog here: How to save file using JFileChooser?