Java JFileChooser choseFile(File selectedFile, String startDir, final String description, final String extension, Component parent, boolean addExtension, boolean forLoad)

Here you can find the source of choseFile(File selectedFile, String startDir, final String description, final String extension, Component parent, boolean addExtension, boolean forLoad)

Description

Opens file chooser.

License

Apache License

Parameter

Parameter Description
selectedFile if not <code>null</code> this file will be selected initially
startDir directory to start with
description description of file to chose

Declaration

public static String choseFile(File selectedFile, String startDir, final String description,
        final String extension, Component parent, boolean addExtension, boolean forLoad) 

Method Source Code


//package com.java2s;
/*/*from w  w w  . java2  s.co m*/
 * Copyright 2007 - 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.util.HashMap;

import java.util.Map;

import javax.swing.JFileChooser;

public class Main {
    /**
     * File to store current directory of file chooser.
     */
    private final static File cdSettings = new File(".cdsettings");

    /**
     * Opens file chooser.
     * 
     * @param selectedFile if not <code>null</code> this file will be selected initially
     * @param startDir directory to start with
     * @param description description of file to chose
     */
    public static String choseFile(File selectedFile, String startDir, final String description,
            final String extension, Component parent, boolean addExtension, boolean forLoad) {
        return choseFile(selectedFile, startDir, description, extension, parent, addExtension, forLoad, true);
    }

    /**
     * Opens file chooser.
     * 
     * @param selectedFile if not <code>null</code> this file will be selected initially
     * @param startDir directory to start with
     * @param description description of file to chose
     */
    public static String choseFile(File selectedFile, String startDir, final String description,
            final String extension, Component parent, boolean addExtension, boolean forLoad,
            final boolean allowZip) {
        String newStartDir = restoreCurrentDir(extension);
        if (newStartDir != null) {
            startDir = newStartDir;
        }
        JFileChooser fileChooser = new JFileChooser(startDir);
        javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() {
            public boolean accept(File pathname) {
                return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(extension)
                        || pathname.getName().toLowerCase().endsWith(extension + ".gz")
                        || pathname.getName().toLowerCase().endsWith(extension + ".zip");
            }

            public String getDescription() {
                if (extension.endsWith(".sql") || extension.endsWith(".xml")) {
                    if (allowZip) {
                        return "*" + extension + " *" + extension + ".zip";
                    }
                }
                return "*" + extension;
            }
        };
        fileChooser.setFileFilter(filter);
        fileChooser.setDialogTitle(description);
        if (selectedFile != null) {
            fileChooser.setSelectedFile(selectedFile);
        }
        fileChooser.setDialogType(forLoad ? JFileChooser.OPEN_DIALOG : JFileChooser.SAVE_DIALOG);
        int returnVal = forLoad ? fileChooser.showOpenDialog(parent) : fileChooser.showSaveDialog(parent);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String fn = "";
            try {
                File f = fileChooser.getSelectedFile();
                String work = new File(".").getCanonicalPath();
                fn = f.getName();
                f = f.getParentFile();
                while (f != null && !f.getCanonicalPath().equals(work)) {
                    fn = f.getName() + File.separator + fn;
                    f = f.getParentFile();
                }
                if (addExtension && !fn.endsWith(extension)) {
                    fn += extension;
                }
                try {
                    storeCurrentDir(extension, fileChooser.getSelectedFile().getParent());
                } catch (Exception e) {
                    // ignore
                }
                return fn;
            } catch (IOException e1) {
                try {
                    fn = fileChooser.getSelectedFile().getCanonicalPath();
                    if (addExtension && !fn.endsWith(extension)) {
                        fn += extension;
                    }
                    return fn;
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    /**
     * Restores current directory of file chooser.
     * 
     * @param key the key of the current directory to restore
     * @return the current directory, or <code>null</code> if no directory has been stored under the key
     */
    @SuppressWarnings("unchecked")
    private static String restoreCurrentDir(String key) {
        if (cdSettings.exists()) {
            try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream(cdSettings));
                String cd = ((Map<String, String>) in.readObject()).get(key);
                in.close();
                return cd;
            } catch (Exception e) {
                // ignore
            }
        }
        return null;
    }

    /**
     * Stores current directory of file chooser.
     * 
     * @param key the key under which to store current directory
     * @param currentDir the current directory
     */
    @SuppressWarnings("unchecked")
    private static void storeCurrentDir(String key, String currentDir) {
        try {
            Map<String, String> cd = new HashMap<String, String>();
            if (cdSettings.exists()) {
                try {
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream(cdSettings));
                    cd = (Map<String, String>) in.readObject();
                    in.close();
                } catch (Exception e) {
                    // ignore
                }
            }
            cdSettings.delete();
            cd.put(key, currentDir);
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cdSettings));
            out.writeObject(cd);
            out.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

Related

  1. chooseFileToRead(Component owner, FileFilter filter, File pathToNavigateTo)
  2. chooseNewFile(final Component parent, final File startingDirectory)
  3. chooseOpenFile(String dir, String fileName, String fileNameExtension, Component parent)
  4. chooseSaveFile(Component parent, File defaultFile, FileFilter filter)
  5. chooseSaveFile(String dir, String initialFile, String fileNameExtension, Component parent)
  6. cleanFileSelector(JFileChooser filterUpdates)
  7. cleanFileSelector(JFileChooser filterUpdates)
  8. configureFileChooser(JFileChooser fchooser, boolean directoryOnly, File selectedFile)
  9. correctSelectedFileExtension(JFileChooser chooser)