Java – Save dialog doesn’t add extension to file

javajfilechoosersavefiledialogswing

I have a button that opens a save dialog window with default extension filters set. When I save a file it creates it in the correct folder, but it doesn't add the extension on the end. How would I go about adding the extension to the end of the file based on the filter?
Here is my save file button code:

    btnNewButton = new JButton("Export File");
    btnNewButton.addActionListener (new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {
            final JFileChooser finder = new JFileChooser();
            finder.setFileFilter(new FileNameExtensionFilter("Board Files", "boa"));
            int returnVal = finder.showSaveDialog(null);
            if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
                java.io.File file = finder.getSelectedFile();
                String file_name = file.toString();
                JOptionPane.showMessageDialog(null, file_name);
                WriteFile data = new WriteFile(file_name);              
                try {
                    data.writeToFile("Testing 1");
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    });

Best Answer

You could add the extension yourself if it is not done already by the user.

String file_name = file.toString();
if (!file_name.endsWith(".boa"))
    file_name += ".boa";
Related Topic