2013-04-10 56 views
0

我正在使用以下方法將文件從一個文件夾(源)移動到另一個(目標)。我添加了一個檢查來查看文件是否存在,該文件返回true,但文件仍然沒有移動到目的地。文件移動不起作用

在這裏,源路徑是:

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

目的地:

C:\用戶\ Avijit \桌面\ RAP009.jrxml和C:\用戶\ Avijit \桌面\ 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(); 
      } 
     } 
    } 

} 

控制檯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! 
+0

你對目標目錄有寫訪問權限? – EJP 2013-04-12 23:07:16

+0

感謝您看一看, 是的,我對目標目錄有寫訪問權限ectory ... – Avijit 2013-04-13 15:29:21

回答

0

根據API爲File

「這種方法的行爲的許多方面是天生的平臺依賴性:重命名操作可能無法從一個文件系統的文件移動到另一個,它可能沒有是原子的,如果具有目標抽象路徑名的文件已經存在,它可能不會成功。返回值應該經常進行檢查,以確保重命名操作成功。」

所以有使用renameTo警告。

不過你的情況很可能會從另一個問題的困擾。如果目錄結構不存在,它會失敗在Java 7中,這是固定的Files.move。這種方法會給予稍微更可靠的性能,即使子目錄不存在問題原來不是罪魁禍首