-2

I want to renamed file 140103122005+0530_Penguins.jpg to Penguins.jpg from same directory.

I have tried renameTo() but it is not working, it requires destination file, I don't have destination file.

Anyone can tell me how to I rename the same file from same directory using Java.

Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74
Hardik Patel
  • 937
  • 3
  • 14
  • 39

4 Answers4

6

Please read the renameTo java doc carefully. It requires abstract destination File object (which does not necessarily mean the file must exist on your system). It is just a indicator to the renameTo() method about the destination file on your system. File documentation clearly says that the file object is abstract representation of the file or directory (the actual file may or may not exist).

Here is a java code snippet for reference:

// This file to be renamed (must exist on your system)
File source = new File("c:/140103122005+0530_Penguins.jpg");

if(source.exists()) {
    // Abstract file path (does not exist)
    File destination = new File ("c:/Penguins.jpg");

    // rename the source file
    source.renameTo(destination);
}
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
1

This is an example

import java.io.*;
public class file {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File f=new File("140103122005+0530_Penguins.jpg");
        f.renameTo(new File("Penguins.jpg"));

    }

}

remaneTo returns boolean so if you want to check whther file has been renamed or not then do System.out.println(f.renameTo(new File("Penguins.jpg")); If you get true then file renamed

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

Maybe you are doing something wrong. It's supposed to be

boolean success = new File("1").renameTo(new File("2"));

Note that according to javadoc it might not be able to move a file from one filesystem to another, and it might not succeed if a file with the destination abstract pathname already exists. renameTo is platform-dependent.

Since Java 7 it is recommended to use platform-independent java.nio.file.Files.move method instead

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Also check whether renaming has succeeded or not by the return paramater of the File.renameTo method. File renaming operation is platform-dependent and may not succeed all the time.

Serdar
  • 383
  • 1
  • 9