Program to Rename a file - in java file IO




java.io.File's renameTo(newFileName) method can be used for renaming file.
Method returns true  - if file is renamed successfully.
Method returns false - if file renaming failed





Program to Rename a file - in java file IO >

import java.io.File;
/** JavaMadeSoEasy.com */
public class RenameFile {
   public static void main(String... args) {
         
          String oldFileName = "c:/myFile.txt";
          String newFileName = "c:/myFileRenamed.txt";
         
          File oldFile = new File(oldFileName);
          File newFile = new File(newFileName);
         
          /*
          * renameTo(newFileName) method can be used for renaming file.
          *
          * Method returns true  - if file is renamed successfully.
          * Method returns false - if file renaming failed
          */
         
          boolean fileRenameSuccess = oldFile.renameTo(newFile);
         
          if(fileRenameSuccess)
                 System.out.println(oldFileName+" renamed successfully to "+ newFileName);
          else
                 System.out.println("File renaming failed");
         
                
         
   }
}
/* OUTPUT
c:/myFile.txt renamed successfully to c:/myFileRenamed.txt
*/



RELATED LINKS>

Create File using createNewFile() method in java file IO


Copy a file in java 2 in ways - use org.apache.commons.io.FileUtils's copyDirectory(sourceDirectory, destDirectory)


Program to Make a file READ ONLY in java



Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO


No comments:

Post a Comment