get Selected File With Extension - Java Swing

Java examples for Swing:JFileChooser

Description

get Selected File With Extension

Demo Code


//package com.java2s;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
    public static File getSelectedFileWithExtension(JFileChooser c) {
        File file = c.getSelectedFile();
        if (c.getFileFilter() instanceof FileNameExtensionFilter) {
            String[] exts = ((FileNameExtensionFilter) c.getFileFilter())
                    .getExtensions();/* www  .j  a v  a 2  s.com*/
            String nameLower = file.getName().toLowerCase();
            for (String ext : exts) {
                if (nameLower.endsWith('.' + ext.toLowerCase())) {
                    return file;
                }
            }
            file = new File(file.toString() + '.' + exts[0]);
        }
        return file;
    }
}

Related Tutorials