Java JFileChooser Filter validateFileName(final File file, final javax.swing.filechooser.FileFilter filter)

Here you can find the source of validateFileName(final File file, final javax.swing.filechooser.FileFilter filter)

Description

Validates the name of a given file, i.e., if the file name doesn't have the proper ending, it will be appended.

License

Apache License

Parameter

Parameter Description
file the file which name has to be validated
filter a file filter containing the definition of the file ending.

Return

a file with validated file name

Declaration

public static File validateFileName(final File file,
        final javax.swing.filechooser.FileFilter filter) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

public class Main {
    /**//from   w w w . j av a  2s  . c  o  m
     * Validates the name of a given file, i.e., if the file name doesn't have the
     * proper ending, it will be appended.
     *
     * @param file the file which name has to be validated
     * @param filter a file filter containing the definition of the file ending.
     * @return a file with validated file name
     */
    public static File validateFileName(final File file,
            final javax.swing.filechooser.FileFilter filter) {
        if (file == null || filter == null || filter.accept(file)) {
            return file;
        }
        // remove wrong file extension if any
        String fileName = file.getName();
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            fileName = fileName.substring(0, index);
        }

        final String extension = filter.toString();

        if (extension.matches("(\\w)*")) {
            String newFileName = fileName + "." + extension;
            File newFile = new File(file.getParent(), newFileName);
            return newFile;
        }//end if

        return file;
    }
}

Related

  1. listAll(File file, javax.swing.filechooser.FileFilter filter)
  2. listAll(File file, javax.swing.filechooser.FileFilter filter)
  3. makeFileFilter(final String desc, final String... types)
  4. makeFileNameExtensionFilter(String[] extensions)
  5. newFileFilter(final String desc, final String[] allowed_extensions)
  6. wrapFilter(final javax.swing.filechooser.FileFilter filter)