File renameTo does not work

Giannis picture Giannis · Apr 1, 2012 · Viewed 38.5k times · Source

I am trying to add an extension to the name of file selected by a JFileChooser although I can't get it to work.

This is the code :

final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File f = fc.getSelectedFile();
            String name =f.getAbsoluteFile()+".txt";
            f.renameTo(new File(name));
            FileWriter fstream;
            try {
                fstream = new FileWriter(f);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write("test one");
                out.close();
            } catch (IOException ex) {
                Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

I can't figure out why this doesn't work. I also tried using getPath() and getCanonicalPath() but the result is the same. The file is created at the directory selected, although without a ".txt" extension.

Answer

Luke Woodward picture Luke Woodward · Apr 2, 2012

It seems to me that all you want to do is to change the name of the file chosen, as opposed to renaming a file on the filesystem. In that case, you don't use File.renameTo. You just change the File. Something like the following should work:

        File f = fc.getSelectedFile();
        String name = f.getAbsoluteFile()+".txt";
        f = new File(name);

File.renameTo attempts to rename a file on the filesystem. For example:

File oldFile = new File("test1.txt");
File newFile = new File("test2.txt");
boolean success = oldFile.renameTo(newFile); // renames test1.txt to test2.txt

After these three lines, success will be true if the file test1.txt could be renamed to test2.txt, and false if the rename was unsuccessful (e.g. test1.txt doesn't exist, is open in another process, permission was denied, etc.)

I will hazard a guess that the renaming you are attempting is failing because you are attempting to rename a directory (you are using a JFileChooser with the DIRECTORIES_ONLY option). If you have programs using files within this directory, or a Command Prompt open inside it, they will object to this directory being renamed.