renameTo作用是文件改名,参数是File类的一个对象,但是这个方法不是一定成功的,有几点需要注意的地方
假如原来的名字为a.txt,需要改名为b.txt,则有如下情况
<span style="white-space:pre"> </span>1. a.txt存在且b.txt不存在的时候renameTo成功
public static void main(String[] args) throws IOException {
File f1 = new File("F:/a.txt");//a.txt已经存在于F盘中
File f2 = new File("F:/b.txt");//b未创建
System.out.println("f1 exists? : " + f1.exists());//f1 exists? : true
System.out.println("f2 exists? : " + f2.exists());//f2 exists? : false
System.out.println(f1.renameTo(f2));//true
//此时改名成功
}
2. a.txt存在且b.txt存在的时候renameTo失败
public static void main(String[] args) throws IOException {
File f1 = new File("F:/a.txt");//a.txt已经存在于F盘中
File f2 = new File("F:/b.txt");//b.txt已经存在于F盘中
System.out.println("f1 exists? : " + f1.exists());//f1 exists? : true
System.out.println("f2 exists? : " + f2.exists());//f2 exists? : true
System.out.println(f1.renameTo(f2));//false
//此时改名失败
}
3. 当a.txt进行读的操作且未关闭输入流的时候renameTo失败
public static void main(String[] args) throws IOException {
File f1 = new File("F:/a.txt");//a.txt已经存在于F盘中
File f2 = new File("F:/b.txt");//b未创建
FileInputStream in = new FileInputStream(f1);
in.read();//a.txt正在进行读的操作
in.close();//若注释掉这句话,renameTo失败
System.out.println("f1 exists? : " + f1.exists());//f1 exists? : true
System.out.println("f2 exists? : " + f2.exists());//f2 exists? : false
System.out.println(f1.renameTo(f2));//true
//此时改名成功
}
4. 当a.txt进行写的操作且未关闭输出流的时候renameTo失败
public static void main(String[] args) throws IOException {
File f1 = new File("F:/a.txt");//a.txt已经存在于F盘中
File f2 = new File("F:/b.txt");//b未创建
FileOutputStream out = new FileOutputStream(f1);
out.write(1);//a.txt正在进行读的操作
out.close();//若注释掉这句话,renameTo失败
System.out.println("f1 exists? : " + f1.exists());//f1 exists? : true
System.out.println("f2 exists? : " + f2.exists());//f2 exists? : false
System.out.println(f1.renameTo(f2));//true
//此时改名成功
}
这是最近遇到的几个问题,可能还有别的原因,欢迎交流