日期:2014-05-20  浏览次数:20808 次

请问如何给文件重命名,File类的renameTo()方法可以吗?
如题,我想给一些文件重新命名,可是使用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,请问是怎么回事啊?~~

------解决方案--------------------
rename要提供完全路径才行

------解决方案--------------------
如ls所述。。。
你不好直接手動改啊。。
------解决方案--------------------
it might not succeed if a file with the destination abstract pathname already exists
目标抽象路径如已存在文件则不会成功
------解决方案--------------------
去掉delete试试
------解决方案--------------------
只要路径下无此文件就行
------解决方案--------------------
false是因为没文件可删
只是现在不能测试
这方法的操作还是platform-dependent的

------解决方案--------------------
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()); 
}
}

}
------解决方案--------------------
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);