Java JFileChooser getSelectedFileWithExtension(JFileChooser c)

Here you can find the source of getSelectedFileWithExtension(JFileChooser c)

Description

Works around a JFileChooser limitation, that the selected file when saving is returned exactly as typed and doesn't take into account the selected file filter.

License

Creative Commons License

Declaration

public static File getSelectedFileWithExtension(JFileChooser c) 

Method Source Code

//package com.java2s;
//License from project: Creative Commons License 

import java.io.File;

import javax.swing.JFileChooser;

import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
    /**/* w w w. ja v a  2  s  . co  m*/
     * Works around a JFileChooser limitation, that the selected file when saving
     * is returned exactly as typed and doesn't take into account the selected
     * file filter.
     */
    public static File getSelectedFileWithExtension(JFileChooser c) {
        File file = c.getSelectedFile();
        if (c.getFileFilter() instanceof FileNameExtensionFilter) {
            String[] exts = ((FileNameExtensionFilter) c.getFileFilter())
                    .getExtensions();
            String nameLower = file.getName().toLowerCase();
            for (String ext : exts) { // check if it already has a valid extension
                if (nameLower.endsWith('.' + ext.toLowerCase())) {
                    return file; // if yes, return as-is
                }
            }
            // if not, append the first one from the selected filter
            file = new File(file.toString() + '.' + exts[0]);
        }
        return file;
    }
}

Related

  1. getPropertiesFile(boolean saving, String startName, String extension, String description)
  2. getSaveAsFile(String defaultName, String currentDirectory, String defaultExtension)
  3. getSaveFile(String message, File defaultFileOrDir, String description, final String... extensions)
  4. getSelectedFiles(final JFileChooser chooser)
  5. getSelectedFiles(JFileChooser chooser)
  6. getSelectedFileWithExtension(JFileChooser c)
  7. getSystemFile(Component owner, int mode, FileFilter[] filters)
  8. getTextFileChooser()
  9. getXmlFileChooser()