JFileChooser(showSaveDialog) cant get the value of

2019-09-21 04:26发布

问题:

Im making a desktop application and it has a JFileChooser(ShowSaveDialog) function.. When I tried to save a sample text file the program didnt get the extension file that I chose.. I'm trying to use the if else or switch statement and I cant figure it out what command will I use to get the string/Int value for the condition if pdf,word or txt extension is chosen as file extension...

public class Save {
    static boolean flag = false;
    public static void main(String[] args) throws IOException, SQLException {
        JFileChooser saveFile = new JFileChooser();
        saveFile.setDialogTitle("Save as"); 

        FileNameExtensionFilter File_ext_txt =
            new FileNameExtensionFilter("Text Documents(*.txt)", "txt");
        FileNameExtensionFilter File_ext_pdf =
            new FileNameExtensionFilter("PDF", "pdf");
        FileNameExtensionFilter File_ext_doc =
            new FileNameExtensionFilter("Word 97-2003 Document", "doc");
        saveFile.addChoosableFileFilter(File_ext_pdf);
        saveFile.addChoosableFileFilter(File_ext_doc);
        saveFile.addChoosableFileFilter(File_ext_txt);

        FileFilter extension = saveFile.getFileFilter();
        int userSelection = saveFile.showSaveDialog(null);
        File File_Path = saveFile.getSelectedFile();
        String fullPath = File_Path.getAbsolutePath();
        String Ext = null;
        if (userSelection == JFileChooser.APPROVE_OPTION){
            if(extension == File_ext_txt){
                Ext = "txt";
            }

            File save = new File(fullPath+"."+Ext);
            System.out.println(extension);
            flag = save.createNewFile();
        }
    }
}

回答1:

I've encountered this issue before. This is a utility function from one of my programs that you can use instead of JFileChooser.getSelectedFile, to get the extension too.

/**
 * Returns the selected file from a JFileChooser, including the extension from
 * the file filter.
 */
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;
}