renameTo()的小问题

今天在研究File的时候,发现renameTo()并没有想象的那么好.
在mac下,例如有文件A,B.
如果两个文件不在同一个文件夹,B要改名成A,那么B会被改名成A并且被移动到原先A所在的目录并且覆盖.

renameTo()仅仅是改名,并不能改变实例.

import  java.io. * ;

/**
 * 文件名的处理
 * 
@author chengyumin
 * String getName(); 获得文件的名称,不包含文件所在的路径。
 * String getPath(); 获得文件的路径。
 * String getAbsolutePath(); 获得文件的绝对路径。
 * String getParent(); 获得文件的上一级目录的名称。
 * String renameTo(File newName); 按参数中给定的完整路径更改当前的文件名。
 * int compareTo(File pathName); 按照字典顺序比较两个文件对象的路径。
 * boolean isAbsolute(); 测试文件对象的路径是不是绝对路径。
 
*/

public   class  ProcessFileName  {

    
public static void main(String[] args)
    
{
        File fileObject1 
= new File("firstFil.txt");
        File fileObject2 
= new File("firstFile.txt");
        
if(!fileObject1.exists()){
            
try{
                
//建立新文件
                fileObject1.createNewFile();
            }
catch(IOException e){
                e.printStackTrace();
            }

        }

        
if(!fileObject2.exists()){
            
try{
                
//建立新文件
                fileObject2.createNewFile();
            }
catch(IOException e){
                e.printStackTrace();
            }

        }

        
        
        System.out.println(
"* * * * * * * * * * * * * * * * * * * * * * * * ");
        System.out.println(
"There are some information of fileObject1's file name:");
        System.out.println(
"fileObject1: " + fileObject1);  
        System.out.println(
"fileObject2: " + fileObject2);
        
        System.out.println(
"file name: " + fileObject1.getName());
        System.out.println(
"file path: " + fileObject1.getPath());
        System.out.println(
"file absolute path: " + fileObject1.getAbsolutePath());
        System.out.println(
"file's parent directory: " + fileObject1.getParent());
        System.out.println(
"file's absoulte path: " + fileObject1.isAbsolute());
        
int sameName = fileObject1.compareTo(fileObject2);
        System.out.println(
"fileObject1 compare to fileObject2: " + sameName);
        fileObject1.renameTo(fileObject2);
        System.out.println(fileObject1);
        System.out.println(fileObject1.exists());
        fileObject1 
= fileObject2;
        System.out.println(fileObject1);
        System.out.println(fileObject1.exists());
        System.out.println(
"file's new name: " + fileObject1.getName());
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值