2011-11-21 74 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(); 
     } 
相关问题