Here you can find the source of chooseSaveFile(String dir, String initialFile, String fileNameExtension, Component parent)
Parameter | Description |
---|---|
dir | The directory which the file chooser works from initially. |
initialFile | The file that is set initially. |
fileNameExtension | The desired file extension. |
parent | The parent component that wants to open the file chooser. |
null
if canceled.
public static File chooseSaveFile(String dir, String initialFile, String fileNameExtension, Component parent)
//package com.java2s; //License from project: Open Source License import java.awt.Component; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; public class Main { /**/* ww w .j ava 2 s. c o m*/ * Opens a file chooser and let the user to either choose or specify a file for saving purpose. * * @param dir The directory which the file chooser works from initially. * @param initialFile The file that is set initially. * @param fileNameExtension The desired file extension. * @param parent The parent component that wants to open the file chooser. * * @return The specified the file, <code>null</code> if canceled. */ public static File chooseSaveFile(String dir, String initialFile, String fileNameExtension, Component parent) { JFileChooser chooser = new JFileChooser(); File selectedFile = null; String selectedFileName = null; File fileDir = null; // if dir is not specified or the dir doesn't exist, use the current directory if (dir == null) { fileDir = new File("."); } else { fileDir = new File(dir); } if (!fileDir.exists()) { fileDir = new File("."); } chooser.setCurrentDirectory(fileDir); if (initialFile != null) { chooser.setSelectedFile(new java.io.File(initialFile)); } if (fileNameExtension != null) { chooser.setFileFilter(new FileNameExtensionFilter(fileNameExtension + " file", fileNameExtension)); } chooser.setDialogTitle("Save File"); boolean isValid = true; do { int chooserState = chooser.showDialog(parent, "Ok"); if (chooserState == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); selectedFileName = selectedFile.getName(); if (fileNameExtension != null) { // 1.append the specified file extension if there is no extension. // 2.append the desired extension if there is an extension which is not the same as specified if (selectedFileName.indexOf('.') == -1 || (selectedFileName.indexOf('.') != -1 && !selectedFileName.endsWith(fileNameExtension))) { selectedFileName += "." + fileNameExtension; } selectedFile = new File(selectedFile.getParentFile(), selectedFileName); } if (selectedFile.exists()) { int choice = JOptionPane.showConfirmDialog(parent, selectedFileName + " already exists. Overwrite it?", "Overwrite File", JOptionPane.YES_NO_OPTION); // If "Yes" is selected if (choice == JOptionPane.YES_OPTION) { isValid = false; } } else { isValid = false; } } else { return null; } } while (isValid); return selectedFile; } }