5、java如何实现移动文件、重命名文件

java.io.File renameTo(File dest) 方法可以用来重命名文件或者移动文件的目录
当成功移动或者重命名方法返回true 否则返回false; 一定要仔细检查这个返回值,这是和平台相关的, 比如说当目录中已有了相同的文件则不能继续移动或者重命名
mac系统中是会覆盖目标文件的 返回true
window系统则不能操作,返回false
代码中从相对、绝对位置测试了重命名操作,而且从不同目录的移动和重命名也做了操作; 每个执行完都给出了结果out out====;
package com.tij.io.file;

import java.io.File;

public class RenameFileJava {

	/**
	 * Rename File or Move File in Java example
	 * @param args
	 */
	public static void main(String[] args) {
		//absolute path rename file
		File file = new File("/Users/GYJ/java.txt");
		File newFile = new File("/Users/GYJ/java1.txt");
		if (file.renameTo(newFile)) {
			System.out.println("rename success");
		} else {
			System.out.println("rename failed");
		}
		//out put: rename success
		
		
		//relative path rename file
		file = new File("DB.properties");
		newFile = new File("NewDB.properties");
		if (file.renameTo(newFile)) {
			System.out.println("rename success");
		} else {
			System.out.println("rename failed");
		}
		//out put: rename success
		
		
		//move file from one directory to another
		file = new File("/Users/GYJ/DB.properties");
		newFile = new File("DB_Move.properties");
		if (file.renameTo(newFile)) {
			System.out.println("move success");
		} else {
			System.out.println("move failed");
		}
		//out put: move success
		
		//when source file is not present(abc.txt is not exists)
		file = new File("/Users/GYJ/abc.txt");
		newFile = new File("gyj.txt");
		if (file.renameTo(newFile)) {
            System.out.println("move success");
        } else {
            System.out.println("move failed");
        }
		//out put:  move failed
		
		
		//when destination already have a file with same name('java1.txt' is already)
		file = new  File( "/Users/GYJ/export.sql" );
        newFile = new  File( "/Users/GYJ/java1.txt" );
        if (file.renameTo(newFile)){
            System.out.println("move success");
        } else {
            System.out.println("move failed");
        }
        //out put:  move failed
	} 

}

你可能感兴趣的:(java)