11

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.

Giannis
  • 5,286
  • 15
  • 58
  • 113
  • 1
    have you checked the result from `renameTo`? This is from the Java documentation "Whether or not this method can move a file from one filesystem to another is platform-dependent. The return value should always be checked to make sure that the rename operation was successful." – twain249 Apr 01 '12 at 18:04
  • Yes its always returning false. The only time it worked is when I set the new File name manually but without including the path : "test.txt". That created a txt containing "test one" but not at the selected directory – Giannis Apr 01 '12 at 18:05
  • Are you sure the target file doesn't already exist? – Jon Skeet Apr 01 '12 at 18:06
  • Yes. A new file is created but without extension. I just do the test on desktop so I can see whats happening. – Giannis Apr 01 '12 at 18:07
  • Can you create a file just using `File f2 = new File(name);`? – twain249 Apr 01 '12 at 18:09
  • LoL yes that actually worked... Should have though about trying.. Guess I can go with that but any guess why renameTo doesn't work? – Giannis Apr 01 '12 at 18:11

5 Answers5

9

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.

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
  • 1
    Yes you are right I ended up just creating a new File using the name(directory) from the Chooser. I just thought the renameTo was an operation that could be used in this case. – Giannis Apr 02 '12 at 09:23
  • In my case, the BufferedReader was open. For this reason the file can't be renamed. – Elidio Marquina May 21 '15 at 00:29
3

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.

Zoltán
  • 21,321
  • 14
  • 93
  • 134
Andrejs
  • 26,885
  • 12
  • 107
  • 96
2

If you want to Rename the file then there is must to close all the object (like FileReader,FileWriter ,FIS ,FOSmeans close the the reading file object and then rename it

Gaikwad
  • 29
  • 1
  • While this might be a valuable hint to solve the problem, an answer really needs a bit more detail than this. Please [edit] to provide example code to show what you mean. Alternatively, consider writing this as a comment instead. – Toby Speight Jun 08 '16 at 21:55
2

You are writing to the wrong file. When you call renameTo, the current file doesn't change it's path. Try this:

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";
        File f2 = new File(name);
        f.renameTo(f2);
        FileWriter fstream;
        try {
            fstream = new FileWriter(f2);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("test one");
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
Andrés Oviedo
  • 1,388
  • 1
  • 13
  • 28
0

You need to create a new instance to refer to the new name of the file

oldFile = new File(newName);
blaucuk
  • 125
  • 1
  • 10