Add .txt extension in JFileChooser
Asked Answered
N

4

8

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?

Ninebark answered 3/1, 2012 at 14:45 Comment(0)
D
7

UPDATE

You pointed me out that the check for existing files doesn't work. I'm sorry, I didn't think of it when I suggested you to replace the BufferedWriter line. Now, replace this:

File sFile = fSave.getSelectedFile();

with:

File sFile = new File(fSave.getSelectedFile()+".txt");

With this replacement, it isn't now needed to replace the line of BufferedWriter, adding .txt for the extension. Then, replace that line with the line in the code you posted (with BufferedWriter out = new BufferedWriter(new FileWriter(sFile)); instead of BufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));).

Now the program should work as expected.

I forgot to mention that you have to comment the line:

sFile.createNewFile();

In this way, you're creating an empty file, with the class File.

Just after this line, there is: BufferedWriter out = new BufferedWriter(new FileWriter(sFile));. With this line, you are creating again the same file. The writing procedure is happening two times! I think it's useless to insert two instructions that are doing the same task.

Also, on the BufferedWriter constructor, you can append a string for the file name (it isn't possible on File constructor), that's the reason why I added +".txt" (the extension) to sFile.

Dissemble answered 3/1, 2012 at 15:6 Comment(6)
Very strange! On my system everything works..I edited the answer.Dissemble
Thank you very much for your useful infos! You are right I did wrote twice the file, there is no reason for this. Now files are correctly saved with suffix ".txtNinebark
There is only one little question still left: I can now save automatically with .txt extension, but I haven't .txt in FileChooser description name. This means that when I save again with a previous file name, it never prompt me file already exist and always overwrite the previous file Example: let's suppose I want to save a file as name = test: now it save as test.txt and create such file. If I want to save another file with the same name, it doesn't get test file as already written since the one saved is now test.txtNinebark
@Albertoacepsut I understood. But you've replaced the string I suggested to you with "BufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));" and comment the line "sFile.createNewFile();" also in the 'else' loop?Dissemble
Yes I did, but the problem is that in this way it never found an already existing file so it never ask for overwrite.Ninebark
No problem, forgive me because I didn't thought first about the checking if the file exists.Dissemble
M
18

I just use this

File fileToBeSaved = fileChooser.getSelectedFile();

if(!fileChooser.getSelectedFile().getAbsolutePath().endsWith(suffix)){
    fileToBeSaved = new File(fileChooser.getSelectedFile() + suffix);
}
Music answered 9/11, 2012 at 12:55 Comment(0)
D
7

UPDATE

You pointed me out that the check for existing files doesn't work. I'm sorry, I didn't think of it when I suggested you to replace the BufferedWriter line. Now, replace this:

File sFile = fSave.getSelectedFile();

with:

File sFile = new File(fSave.getSelectedFile()+".txt");

With this replacement, it isn't now needed to replace the line of BufferedWriter, adding .txt for the extension. Then, replace that line with the line in the code you posted (with BufferedWriter out = new BufferedWriter(new FileWriter(sFile)); instead of BufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));).

Now the program should work as expected.

I forgot to mention that you have to comment the line:

sFile.createNewFile();

In this way, you're creating an empty file, with the class File.

Just after this line, there is: BufferedWriter out = new BufferedWriter(new FileWriter(sFile));. With this line, you are creating again the same file. The writing procedure is happening two times! I think it's useless to insert two instructions that are doing the same task.

Also, on the BufferedWriter constructor, you can append a string for the file name (it isn't possible on File constructor), that's the reason why I added +".txt" (the extension) to sFile.

Dissemble answered 3/1, 2012 at 15:6 Comment(6)
Very strange! On my system everything works..I edited the answer.Dissemble
Thank you very much for your useful infos! You are right I did wrote twice the file, there is no reason for this. Now files are correctly saved with suffix ".txtNinebark
There is only one little question still left: I can now save automatically with .txt extension, but I haven't .txt in FileChooser description name. This means that when I save again with a previous file name, it never prompt me file already exist and always overwrite the previous file Example: let's suppose I want to save a file as name = test: now it save as test.txt and create such file. If I want to save another file with the same name, it doesn't get test file as already written since the one saved is now test.txtNinebark
@Albertoacepsut I understood. But you've replaced the string I suggested to you with "BufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));" and comment the line "sFile.createNewFile();" also in the 'else' loop?Dissemble
Yes I did, but the problem is that in this way it never found an already existing file so it never ask for overwrite.Ninebark
No problem, forgive me because I didn't thought first about the checking if the file exists.Dissemble
F
4

This is a utility function from one of my programs that you can use instead of JFileChooser.getSelectedFile, to get the extension too.

/**
 * Returns the selected file from a JFileChooser, including the extension from
 * the file filter.
 */
public static File getSelectedFileWithExtension(JFileChooser c) {
    File file = c.getSelectedFile();
    if (c.getFileFilter() instanceof FileNameExtensionFilter) {
        String[] exts = ((FileNameExtensionFilter)c.getFileFilter()).getExtensions();
        String nameLower = file.getName().toLowerCase();
        for (String ext : exts) { // check if it already has a valid extension
            if (nameLower.endsWith('.' + ext.toLowerCase())) {
                return file; // if yes, return as-is
            }
        }
        // if not, append the first extension from the selected filter
        file = new File(file.toString() + '.' + exts[0]);
    }
    return file;
}
Fryer answered 24/9, 2013 at 14:34 Comment(0)
A
1

I've done this function for this purpose :

/**
 * Add extension to a file that doesn't have yet an extension
 * this method is useful to automatically add an extension in the savefileDialog control
 * @param file file to check
 * @param ext extension to add
 * @return file with extension (e.g. 'test.doc')
 */
private String addFileExtIfNecessary(String file,String ext) {
    if(file.lastIndexOf('.') == -1)
        file += ext;

    return file;
}

Then you can use the function for example in this way :

JFileChooser fS = new JFileChooser();
String fileExt = ".txt";
addFileExtIfNecessary(fS.getSelectedFile().getName(),fileExt)
Ashia answered 3/1, 2012 at 14:55 Comment(2)
thanks but I have Exception run: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at provegrafica.ProvaFramePop.createTxt(ProvaFramePop.java:145)Ninebark
Wouldn't this fail if the filename contains "."?Zofiazoha

© 2022 - 2024 — McMap. All rights reserved.