0

I'm using the following method to moves files from one folder(source) to another(destination). I have added a check to see if the file exists which is returning true, but still the file is not moving to the destination.

Here the source paths are:

C:\App_v10.4\RAP009.jrxml and C:\App_v10.4\RAP009.jasper

Destination :

C:\Users\Avijit\Desktop\RAP009.jrxml and C:\Users\Avijit\Desktop\RAP009.jasper

private void moveFile(List<String> source, String destination)
        throws IOException {

    if (null != source && !source.isEmpty()) {
        for (String path : source) {
            try {
                File file = new File(path);
                System.out.println(path);
                System.out.println("File :" + file.exists());
                System.out.println(new File(destination + file.getName()));
                System.out.println(file.getCanonicalPath());
                System.out.println(file.getAbsolutePath());
                System.out.println(file.getPath());
                if (file.renameTo(new File(destination + file.getName()))) {
                    System.out.println("File is moved successful!");
                } else {
                    System.out.println("File has failed to move!");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

Console O/P :

C:\App_v10.4\RAP009.jrxml

File :true
C:\Users\Avijit\Desktop\RAP009.jrxml

C:\App_v10.4\RAP009.jrxml

C:\App_v10.4\RAP009.jrxml

C:\App_v10.4\RAP009.jrxml

File has failed to move!

C:\App_v10.4\RAP009.jasper

File :true

C:\Users\Avijit\Desktop\RAP009.jasper

C:\App_v10.4\RAP009.jasper

C:\App_v10.4\RAP009.jasper

C:\App_v10.4\RAP009.jasper

File has failed to move!
tshepang
  • 12,111
  • 21
  • 91
  • 136
Avijit
  • 1
  • 2

1 Answers1

0

According to the api for File,

"Many aspects of the behavior of this method are inherently platform-dependent: 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."

So there is the warning with using renameTo.

However your case is likely to suffer from yet another problem. If the directory structure does not exist, it will fail. In Java 7, this is fixed with Files.move. This method will give slightly more reliable performance, even if the subdirectories don't exists problem turns out not to be the culprit.

demongolem
  • 9,474
  • 36
  • 90
  • 105