Set default saving extension with JFileChooser
Asked Answered
H

5

17

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?
Hallah answered 9/6, 2013 at 14:30 Comment(2)
I just wonder how should program react if user gives name like something.xml.xml.xml.Provided
only problem with putting ` + ".xml"` is that if you reopen that file then it will be fileName.xml.xmlSeamy
M
21

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?

Marty answered 9/6, 2013 at 15:17 Comment(2)
I would argue it IS JFileChooser sucking. Most UIs automatically add the extension unless you select "All Files" in the drop-down in which case it'll leave their extensions alone. This is what JFileChooser should do, and this is the behaviour I want to replicate in my app (as it's what people are familiar with). I guess this is impossible without diving into JFileChooser's internals?Indulgence
You need to implement your own file-chooser for the behavior that you want. What you describe is not any kind of standard, though, and I feel pretty annoyed when I write out a file extension and then the program adds its own extension (and then the OS hides it and I have a file that's mysteriously broken because some developer thought they were helping).Marty
C
14

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.

Catching answered 24/7, 2015 at 19:50 Comment(0)
X
3

How about something like this:

    else if (e.getSource() == saveMenu) {
        int returnVal = chooser.showSaveDialog(Simulator.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();

            String fname = file.getAbsolutePath();

            if(!fname.endsWith(".xml") ) {
                file = new File(fname + ".xml");

            if(!file.createNewFile()) {
                /*check with user??*/
            }
Xerox answered 9/6, 2013 at 15:34 Comment(1)
If you want to replace current file extension, just add fname = fname.substring(0, fname.lastIndexOf('.')); before file = new File(fname + ".xml");Emersed
E
1

You should try this:

if(!file.getName().contains(".")) file = new File(file.toString() + ".xml");
Enantiomorph answered 20/9, 2017 at 16:2 Comment(0)
S
0

You should try this. I did this and it worked.

FileOutputStream fileOut =  new FileOutputStream(file1+".xml");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
Severe answered 14/4, 2015 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.