如题,我想给一些文件重新命名,可是使用renameTo()方法却没有效果以下是我重命名部分的代码:
f=new File(filename+dm+"2.xml");
f2=new File(filename+dm+".xml");
if(f2.exists())f2.delete();
boolean t=f.renameTo(f2);
System.out.println(t);renameTo()的返回值总是false,请问是怎么回事啊?~~

解决方案 »

  1.   

     rename要提供完全路径才行
      

  2.   

    it might not succeed if a file with the destination abstract pathname already exists
    目标抽象路径如已存在文件则不会成功
      

  3.   

    呵呵,能手动改就不会想要写程序来做了阿刚试了一下用getAbsolutePath()方法取出一个文件的绝对路径,然后进行renameTo()还是返回的false啊
    代码如下
    f=new File(filename+dm+"2.xml");
    String path=f.getAbsolutePath();
    String path2=path.replaceAll("2.xml", ".xml");
    System.out.println("文件路径"+path);
    System.out.println("文件路径2"+path2);
    f2=new File(path2);
    if(f2.exists())f2.delete();
    boolean t=f.renameTo(f2);
    System.out.println("重命名成功:"+t);运行结果:
    文件路径E:\dzhxml\Fhzs\SZ0009972.xml
    文件路径2E:\dzhxml\Fhzs\SZ000997.xml
    重命名成功:false
      

  4.   

    if(f2.exists())f2.delete();目标文件不存在阿,我中间这句就是为了检测目标文件是否存在,如果存在就删除掉
      

  5.   

    去掉delete以后还是不行,而且发现对f使用delete()方法的返回值也是false,奇怪阿.....
      

  6.   

    false是因为没文件可删
    只是现在不能测试
    这方法的操作还是platform-dependent的
      

  7.   

    import java.io.File;
    public class rename { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
    File f=new File("c:\\2.xml"); 
    File f2=new File("c:\\xu.xml"); 
    if(f2.exists()) f2.delete(); 
    boolean t=f.renameTo(f2); 
    System.out.println(t); 
    }catch(Exception   e){
    System.out.println(e.getMessage()); 
    }
    }}
      

  8.   

    f=new File(filename+dm+"2.xml"); 
    f2=new File(filename+dm+".xml"); 
    //(f2.exists())f2.delete();这句要去掉,否则你需要重新new f2对象空间。
    boolean t=f.renameTo(f2); 
    System.out.println(t); 
      

  9.   

    谢谢两位的指点,我发现问题出在这里了
    public void rename(File f){
    String path=f.getAbsolutePath();
    String path2=path.replaceAll("2.xml", ".xml");
    System.out.println("文件路径"+path);
    System.out.println("文件路径2"+path2);
    File ff=new File(path2);
    //if(f2.exists())f2.delete();
    boolean t=f.renameTo(ff);
    System.out.println("重命名成功:"+t);
       }如果用rename(new File("e://dzhxml//Fhzs//SH6000482.xml")),那么rename成功
    如果用rename(new File("e://dzhxml//Fhzs//"+dm+"2.xml")),其中dm="SH600048",那么rename失败
    按道理来说这两个new File()应该是一样的阿,怎么会出现这种情况呢...迷糊了,请指教!