使用renameTo()进行移动和重命名操作,注:该方法无法覆盖重名文件,需用delete()删除再使用renameTo()操作。
1 package eg2; 2 3 import java.io.File; 4 import java.util.Scanner; 5 6 /****************** 7 * 文件的移动和重命名 8 *******************/ 9 public class Test2_1 { 10 11 static Scanner sc = new Scanner(System.in); 12 13 public static void main(String[] args) { 14 // TODO Auto-generated method stub 15 16 System.out.println("请输入文件当前目录:"); 17 String oldpath = sc.next(); 18 System.out.println("请输入目的目录:"); 19 String newpath = sc.next(); 20 File newpaths = new File(newpath); 21 if (newpaths.exists()) { 22 System.out.println("请输入要移动的文件名:"); 23 String files = sc.next(); 24 removefile(files, oldpath, newpath); 25 } else 26 System.out.println("该目录不存在!"); 27 } 28 29 public static void removefile(String filename, String oldpath, String newpath) { 30 if (!oldpath.equals(newpath)) { 31 File oldfile = new File(oldpath + "/" + filename); 32 File newfile = new File(newpath + "/" + filename); 33 if (oldfile.exists()) { 34 if (newfile.exists()) { 35 System.out.println("文件已存在,是否覆盖?1:是;2:不是。"); 36 int key = sc.nextInt(); 37 if (key == 1) { 38 newfile.delete(); 39 oldfile.renameTo(newfile); 40 System.out.println("文件移动成功,是否需要重命名该文件?1:是;2:不是。"); 41 int rename = sc.nextInt(); 42 if (rename == 1) { 43 System.out.println("请输入新的文件名:"); 44 String filenames = sc.next(); 45 renameFile(newpath, filename, filenames); 46 } 47 } else { 48 System.out.println("已取消移动!"); 49 } 50 } else { 51 oldfile.renameTo(newfile); 52 System.out.println("文件移动成功,是否需要重命名该文件?1:是;2:不是。"); 53 int rename = sc.nextInt(); 54 if (rename == 1) { 55 System.out.println("请输入新的文件名:"); 56 String filenames = sc.next(); 57 renameFile(newpath, filename, filenames); 58 } 59 } 60 } else 61 System.out.println("文件不存在!"); 62 63 } 64 } 65 66 public static void renameFile(String path, String oldFileName, String newFileName) { 67 if (!oldFileName.equals(newFileName)) { 68 File oldfile = new File(path + "/" + oldFileName); 69 File newfile = new File(path + "/" + newFileName); 70 oldfile.renameTo(newfile); 71 } else { 72 System.out.println("新名称与旧名称一致,是否重新命名?1:是;2:取消修改。"); 73 int key = sc.nextInt(); 74 if (key == 1) { 75 System.out.println("请输入新的文件名:"); 76 String newFileNames = sc.next(); 77 renameFile(path, oldFileName, newFileNames); 78 } 79 } 80 } 81 }