Question

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());
                }
            }
        }
    });
Était-ce utile?

La solution

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top