Add .txt extension in JFileChooser

Alberto acepsut picture Alberto acepsut · Jan 3, 2012 · Viewed 29.3k times · Source

I have a method that get text from a JTextArea, create a file and write text on it as code below:

public void createTxt() {

    TxtFilter txt = new TxtFilter();

    JFileChooser fSave = new JFileChooser();

    fSave.setFileFilter(txt);
    int result = fSave.showSaveDialog(this);
    if(result == JFileChooser.APPROVE_OPTION) {
        File sFile = fSave.getSelectedFile();
        FileFilter selectedFilter = fSave.getFileFilter();

        String file_name = sFile.getName();
        String file_path = sFile.getParent();

        try{
            if(!sFile.exists()) {
                sFile.createNewFile();
                BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
                out.write(jTextArea1.getText());
                out.close();
                JOptionPane.showMessageDialog(null, "Warning file • " + file_name + " • created succesfully in \n" + file_path);    
            } else {
                String message = "File • " + file_name + " • already exist in \n" + file_path + ":\n" + "Do you want to overwrite?";
                String title = "Warning";
                int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
                if(reply == JOptionPane.YES_OPTION){
                    sFile.delete();
                    sFile.createNewFile();
                    BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
                    out.write(jTextArea1.getText());
                    out.close();
                    JOptionPane.showMessageDialog(null, "File • " + file_name + " • overwritten succesfully in \n" + file_path);

                }
            }
        }
       catch(IOException e) {
           System.out.println("Error");
       }
    }
}

and a txt file filter

public class TxtFilter extends FileFilter{
    @Override
    public boolean accept(File f){
        return f.getName().toLowerCase().endsWith(".txt")||f.isDirectory();
    }
    @Override
    public String getDescription(){
        return "Text files (*.txt)";
    }
}

The file filter for txt works fine but what I want is to add ".txt" extension when I type file name.

How to I have to modify my code?

Answer

gjosse picture gjosse · Nov 9, 2012

I just use this

File fileToBeSaved = fileChooser.getSelectedFile();

if(!fileChooser.getSelectedFile().getAbsolutePath().endsWith(suffix)){
    fileToBeSaved = new File(fileChooser.getSelectedFile() + suffix);
}