2014-06-12 73 views
2

我希望將這些文件從一個文件夾複製到子文件夾,然後重命名文件名,我得到創建子文件夾,並得到了文件名重命名,用這部分:快速複製的文件

for (int i = 0; i < list.length; i++) { 
    String oldDir = path2; 
    String oldName = list[i].toString(); 

    String newDir =oldDir+"\\sub"; 
    File pDir = new File(newDir); 
    pDir.mkdir(); 
    String fileName = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss") 
    .format(new Date()); 
    String newName = fileName+"_"+list[i].getName(); 

    File f = new File (oldDir, list[i].getName()); 
    if(f.renameTo(new File(newDir + newName))){ 
     System.out.println("File is moved successful!"); 
    }else{ 
     System.out.println("File is failed to move!"); 
    }} 
} 

但我不能把這個重命名的文件複製到新的子文件夾中,它將它重命名爲父目錄而不是舊文件名,我在哪裏錯誤?

回答

0

使用此代碼:

public static void copyFile(File sourceFile, File destFile) { 
    try { 
     if (!sourceFile.exists()) { 
      return; 
     } 
     if (!destFile.exists()) { 
      destFile.createNewFile(); 
     } 
     FileChannel source = null; 
     FileChannel destination = null; 
     source = new FileInputStream(sourceFile).getChannel(); 
     destination = new FileOutputStream(destFile).getChannel(); 
     if (destination != null && source != null) { 
      destination.transferFrom(source, 0, source.size()); 
     } 
     if (source != null) { 
      source.close(); 
     } 
     if (destination != null) { 
      destination.close(); 
     } 
    } catch (IOException e) { 

    } 
} 

第一個參數(sourceFile)是文件,你想拷貝和destFile是要複製到(這將是你的子文件夾)的文件,並使用新的文件名

0

有某些情況下,文檔File.renameTo()當文件不能被移動:

 * 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. 
1

你的錯誤是在日E「如果」行:

if(f.renameTo(new File(newDir + newName))){ 

的問題是,如果引用的文件對象,它是舊文件,F,然後將其重命名爲新的目錄,它不工作(如NKukhar說明)因爲它可能不會按照您的意圖複製文件。