Renaming and deleting a file in Java

Rename:

Use the method renameTo in the File class. If the destination folder is different from the source folder, it will move the file to the destination folder. Eg.

import java.io.*;
 
public class FileRename 
{
   public static void main(String []args) {
      File file = new File("c:\test.txt");
 
      file.renameTo(new File("c:\test2.txt"));
 
      System.out.println(file.getName());
   }

}

Notice that, after renaming, getName returns the old filename. Bug? Anyone?

Delete:

Use the method delete in the File class. Eg.

import java.io.*;
 
public class FileDelete
{
   public static void main(String []args) {
      File file = new File("c:\test.txt");
 
      file.delete();
   }
}