samnaction
samnaction

Reputation: 1254

How to move an already moved file to new directory

I am trying to move a single File between folders. I use file.renameTo() to move my file.

//moving the file to new folder
//this is success 
boolean fileMoveCompleted = finalFileToProcess
                        .renameTo(new File(processingFolderName
                                + File.separator + finalFileToProcess.getName()));

//now trying to move the renamed file to another folder
//this is failing
 fileMoveCompleted = finalFileToProcess
                                .renameTo(new File(successFolderName
                                        + File.separator
                                        + finalFileToProcess.getName()));

After the first renameTo the file path still points to the older path. Is there any way I can move the same file to another directory ?

Upvotes: 1

Views: 58

Answers (1)

Markus
Markus

Reputation: 2053

You need to keep the first target file of renameTo as reference and rename that one.

File processing = new File(processingFolderName 
                        + File.separator 
                        + finalFileToProcess.getName());
boolean fileMoveCompleted = finalFileToProcess.renameTo(processing);
File finished = new File(successFolderName 
                        + File.separator 
                        + finalFileToProcess.getName());
fileMoveCompleted = processing.renameTo(finished);

But as File.renameTo's JavaDoc suggests, you should better use Files.move.

Upvotes: 1

Related Questions