Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File renameTo does not work

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.

like image 962
Giannis Avatar asked Apr 01 '12 18:04

Giannis


2 Answers

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.

like image 93
Luke Woodward Avatar answered Oct 29 '22 15:10

Luke Woodward


You could also use the Files.move utility from Google Guava libraries to rename a file. Its easier than writing your own method.

From the docs:

Moves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.

like image 25
Andrejs Avatar answered Oct 29 '22 15:10

Andrejs