JFileChooser(showSaveDialog) cant get the value of the extension file chosen

依然范特西╮ 提交于 2020-01-17 15:40:09

问题


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;
}


来源:https://stackoverflow.com/questions/16846078/jfilechoosershowsavedialog-cant-get-the-value-of-the-extension-file-chosen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!