Save dialog doesn't add extension to file

11,459

Solution 1

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

Solution 2

The filter is just for filtering the existing files inside the selected folder. Since there is the possibility to have more than one extension inside the filter, only you can decide which extension to add.

The adding itself could be done like in the answer above.

Share:
11,459
Dan
Author by

Dan

Updated on June 15, 2022

Comments

  • Dan
    Dan almost 2 years

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