Java JFileChooser getSelectedFileWithExtension(JFileChooser c)

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

Description

Returns the selected file from a JFileChooser, including the extension from the file filter.

License

Open Source License

Declaration

public static File getSelectedFileWithExtension(JFileChooser c) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
    /**//  w w w .java  2s. c  om
     * Returns the selected file from a JFileChooser, including the extension from
     * the file filter.
     * From: http://stackoverflow.com/a/18984561
     */
    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 extension from the selected filter
            file = new File(file.toString() + '.' + exts[0]);
        }
        return file;
    }
}

Related

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