Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default saving extension with JFileChooser

I'm trying to save a file using JFileChooser. However, I seem to be having some trouble with it. Here's my code:

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

        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

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

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

        if (result == chooser.APPROVE_OPTION) {
            writeToXML(chooser.getSelectedFile());
        }

    }

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

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

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

So my questions are:

  • How can I make the JFileChooser 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?
like image 707
SaintLike Avatar asked Jun 09 '13 14:06

SaintLike


People also ask

What is JFileChooser in Java?

JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser , see How to Use File Choosers, a section in The Java Tutorial.

What is FileNameExtensionFilter in Java?

public final class FileNameExtensionFilter extends FileFilter. An implementation of FileFilter that filters using a specified set of extensions. The extension for a file is the portion of the file name after the last ".". Files whose name does not contain a "." have no file name extension.

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.


2 Answers

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?

like image 65
Nathaniel Waisbrot Avatar answered Sep 17 '22 13:09

Nathaniel Waisbrot


Just to make things clear as to how to use the JFileChooser to save files.

//set it to be a save dialog
 chooser.setDialogType(JFileChooser.SAVE_DIALOG);
//set a default filename (this is where you default extension first comes in)
 chooser.setSelectedFile(new File("myfile.xml"));
//Set an extension filter, so the user sees other XML files
 chooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));

now the user was encouraged to save the item as an xml file in this example, but they may not have actually set it.

if(chooser.showSaveDialog(this) == jFileChooser.APPROVE_OPTION) {
    String filename = chooser.getSelectedFile().toString();
    if (!filename .endsWith(".xml"))
        filename += ".xml";

    //DO something with filename
}

This is the most simple case, if you have multiple possible file formats, then you should catch the selected filter, verify THAT extension, and also save the file according to the selected format. but if you are doing that, you are probably an advanced java programmer and not utilizing this post.

like image 30
DiamondDrake Avatar answered Sep 18 '22 13:09

DiamondDrake