Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving files is not working in java [duplicate]

Tags:

java

i'm trying in a loop to move files after they are loaded and processed...when I test moving file part individually it works but when I do it all at once it does not work.

Bellow works fine, but moves directories also but I want only the file to be moved.

public class moveFiles {

    public static void main(String[] args) {
        String getFilesFrom = "D:\\show\\from";
        String destDir = "D:\\show\\to\\";

        File srcFile = new File(getFilesFrom);

        srcFile.renameTo(new File(destDir, srcFile.getName())); 

    }

}

The code that I have which is not working the moving part is bellow.

for (File child : file.listFiles()) {
    if(extensionFilter.accept(child)) { 
        fr = new FileReader(child);
        cm.copyIn("COPY ct"+addExtraZero+month+" FROM STDIN WITH DELIMITER ',' csv", fr);   
    } else {
        System.out.println("No File is elgible to be loaded");
        break;
    }
    getNumberOfFilesProcessed++;
    System.out.println("Loading now " + child.getName());
    child.renameTo(new File(moveFilesTo, child.getName()));
}
System.out.println("Number of files Loaded is: " + getNumberOfFilesProcessed);

The above code is:

  • get files from source directory,
  • loaded it in database
  • print files name that it loads
  • get count of files loaded

which all above works but the last part which is to move files to other directory after loading is not working bellow is the section of files that suppose to move the file the loop.

child.renameTo(new File(moveFilesTo, child.getName()));

scratching my heads for two hours any help will be appreciated.

like image 343
hi4ppl Avatar asked Jan 31 '26 06:01

hi4ppl


1 Answers

From description of File.renameTo() (emphasis mine):

The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful

Add:

if( !child.renameTo(new File(moveFilesTo, child.getName())) )
    System.out.println("Could not move file");

Or try using move(Path, Path, CopyOption...) method, as this has more options (using File.toPath()).

like image 151
Drgabble Avatar answered Feb 02 '26 21:02

Drgabble