Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move and Rename file using Java

Tags:

java

i want to move and rename a file using Java. I tried this code but it fails to rename: Any Help please, Thank you

public class MoveAndRenameFile {

public MoveAndRenameFile(){
    //Current Date and Time  
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    {
        File file = new File("C:\\FolderA\\Client.pdf");
        File newFile = new File(("C:\\FolderB\\Clientx.pdf"));
        if(file.renameTo(newFile)+dateFormat.format(date)){
            System.out.println("File rename success");;
        }else{
            System.out.println("File rename failed");
        }

    }
like image 534
user3610075 Avatar asked Jan 10 '23 10:01

user3610075


1 Answers

The File I/O API was changed and improved considerably with Java 7. One of the problems with the legacy (pre Java 7) File API was that:

• The rename method didn't work consistently across platforms

The NIO.2 API (File API introduced with Java 7) way of renaming files is using Files.move:

Files.move(file, newFile, StandardCopyOption.REPLACE_EXISTING);

The section Mapping java.io.File Functionality to java.nio.file in Legacy File I/O Code will help you to replace your old file operations with new ones.

like image 163
Nivas Avatar answered Jan 18 '23 16:01

Nivas