2011-11-21 73 views
1

我想將文件從一個路徑移動到另一個路徑,但不是移動它將文件複製到新位置。 請提供任何提示將文件移動到新位置,然後刪除上一個文件

在此先感謝

MovePngToPreviewDir pngToPreviewDir = new MovePngToPreviewDir(null, "png"); 

       File[] listOfPNGFiles = RootDir.listFiles(pngToPreviewDir); 

       for(File file:listOfPNGFiles){ 
        Log.e("PNG = ",file.getAbsolutePath()); 
        Log.e("PNG = ",file.getName()); 
        if(previewDiagramDir == null){ 
         Log.e("Preview Diagram Dir is NULL","Preview Diagram DIR is NULL"); 
        } 
        if(file!= null && previewDiagramDir != null){ 
         Log.e("Preview Diagram Dir",previewDiagramDir.getAbsolutePath()+"/"); 

         if(file.renameTo(new File(previewDiagramDir, file.getName()))){ 
          Log.e("PNG File is successfully Moved",file.getName()); 



         }else{ 
          Log.e("Error in Moving PNG File","Error in Moving PNG file"); 
         } 


        }else{ 

        } 

回答

4

如果你想將文件複製到其他位置,則可以使用file.renameTo()方法File類,關係到你的istance對象file,試圖這樣的:

file.renameTo(new File("new_directory_to_copy_file"+file.getName())); 

複製文件後,可以將其刪除與file.delete();

注意

boolean del = file.delete(); 

if(del) System.out.println("File "+file.getName()+" deleted!"); 
else System.out.println("File "+file.getName()+"not deleted!"); 

關於File類API:http://download.oracle.com/javase/6/docs/api/java/io/File.html

1

使用file.delete()將文件複製到另一個位置之後,使其完全移動到新位置。

0

我已經將文件移動到該delete()返回boolean對象的方法,那麼你就可以檢查正確的文件刪除目標目錄,移動之後從三個方面刪除源文件夾中移動的文件,最後在我的項目中使用第三種方法。

1的方法:

File folder = new File("SourceDirectory_Path"); 
File[] listOfFiles = folder.listFiles(); 
for (int i = 0; i < listOfFiles.length; i++) { 
Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName())); 
} 
System.out.println("SUCCESS"); 

第二個辦法:

Path sourceDir = Paths.get("SourceDirectory_Path"); 
Path destinationDir = Paths.get("DestinationDerectory_Path"); 
    try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){ 
    for (Path path : directoryStream) { 
     File d1 = sourceDir.resolve(path.getFileName()).toFile(); 
     File d2 = destinationDir.resolve(path.getFileName()).toFile(); 
     File oldFile = path.toFile(); 
     if(oldFile.renameTo(d2)){ 
      System.out.println("Moved"); 
     }else{ 
      System.out.println("Not Moved"); 
     } 
    } 
}catch (Exception e) { 
    e.printStackTrace(); 
} 

第三屆方法:

Path sourceDirectory= Paths.get(SOURCE_FILE_PATH); 
     Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH); 
     try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) { 
      for (Path path : directoryStream) {          
       Path dpath = destinationDirectory .resolve(path.getFileName());          
       Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING); 
      } 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
相關問題