java中重命名文件并移动文件

今天遇到一个需求,需要把有1000行的文件重命名为*.done并移动到新的目录当中, 本来很简单的需求,实际也真的很简单, 浪费很多时间太不应该, 代码如下.

	private void archiveAuditLogFile(String oldFileAbsolutePath){
		String archiveFolderPath = this.auditBasicPath + DateUtils.format(new Date(), "yyyyMM");
		File dirFile = null;
		try{
			dirFile = new File(archiveFolderPath);
			if (!(dirFile.exists())&&!(dirFile.isDirectory())) {
                boolean creadok = dirFile.mkdirs();
                if (creadok) {
                   System.out.println( "===========create archive folder successfully!===============:"+dirFile.getName());
               } else {
                   System.out.println( "====================err: failed to create archive folder==============" );                    
               } 
			}else{
				System.out.println("==================the folder "+ archiveFolderPath + "alredy exist!=========");
			}
			
			File file = new File(oldFileAbsolutePath);			
			File newFile = new File(archiveFolderPath+ File.separator+file.getName()+".done");
			file.renameTo(newFile);
			System.out.println("new file Name :"+ newFile.getName()+"\t file path:"+newFile.getParent());

		}catch(Exception se){
			se.printStackTrace();
		}
	}


简单而言就是先根据旧文件的绝对路径创建file, 再指定新文件的绝对路径(包含新的目录和文件名即可), 然后remaneTo就搞定了!

你可能感兴趣的:(java,重命名文件)