Java中如何将文件移动到另一个目录

时间:2020-02-23 14:34:21  来源:igfitidea点击:

在本教程中,我们将看到如何将文件移动到Java中的另一个目录。
我们将使用java.io.file的重命名(文件dest)来执行它。

在下面的示例中,我们将从/用户/igi/Desktop/foller1移动到/用户/igi/Desktop/follop2中的Config_new.properties。

Java程序:

package org.igi.theitroad;
 
import java.io.File;
/*
 * @Author : igi Mandliya
 */
public class MoveFileMain {
 
 public static void main(String[] args) {
  
  System.out.println("-----------------");
  //when source file is present
  File fileSrc = new File("/Users/igi/Desktop/Folder1/config_new.properties");
  File newFileDest = new File("/Users/igi/Desktop/Folder2/"+fileSrc.getName());
  if(fileSrc.renameTo(newFileDest)){
   System.out.println("Move operation is successful");
  }else{
   System.out.println("Move operation is unsuccessful");
  }
  System.out.println("-----------------");
  //when source file is not present
  File file = new File("/Users/igi/notExists.txt");
  File newFile = new File("xyz.txt");
  if(file.renameTo(newFile)){
   System.out.println("Move operation is successful");
  }else{
   System.out.println("Move operation is unsuccessful");
  }
  System.out.println("-----------------");
 
 }
 
}

当我在上面的程序上运行时,我得到了以下输出:

----------------
Move operation is successful
----------------
Move operation is unsuccessful
----------------