开发者

Filechooser: get selected postfix

I have the following Method. In the fileschooser I can select a file or just type in the name to create a new one. This is working fine.

But how can I check programmatically which extension was chosen in the drop down list?

I need it to append it to the filename. And to distinguish what to do depending on the fileformat.

Or is there an easier solution with a filechooser?

Thanks in advance!

public static String startNewFile(Viewer parentFrame) {
    File savedFile = null;
    String savedFileName = null;
    int extIndex = -1;
    String tempExt = null;
    String savedPath = null;
    final StringBuffer sb = new StringBuffer(128);

    try {
        String ext1 = "a";
        String ext2 = "b";
        String ext3 = "c";
        fileFilter.removeAllExtensions();
        fileFilter.addExtension(ext1);
        fileFilter.addExtension(ext2);
        fileFilter.addExtension(ext3);

        fileChooser.setFileFilter(fileFilter);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setDialogTitle("Log file name");
        final File directory = new File(Logger.getLogDirectory());
        if (!directory.exists()) {
            directory.mkdir();
        }
        fileChooser.setCurrentDirectory(directory);
        final int returnVal = fileChooser.showSaveDialog(parentFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            savedFile = fileChooser.getSelectedFile();
            savedFileName = savedFile.getName();
            extIndex = savedFileName.lastIndexOf(".");
            tempExt = savedFileName.substring(extIndex + 1);
            savedPath = (fileChooser.getSelectedFile()).getAbsolutePath();
            if (!ext.equals(tempExt)) {
                sb.append(savedPath);
                sb.append(".");
                sb.append(ext);
                savedPath = sb.toString();
            }

            if (!setWriteFileName(savedPath)) {
                return null;
            }

        } else {
            return null;
        }
    } catch (IOException e) {
        e.printStackTrace开发者_运维知识库();
        ErrorPopUp.setMessage(e.toString()).setVisible(true);
        return null;
    }
    return savedPath;
}


You can use getFileFilter() which should return the currently selected file filter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜