java的File类的renameTo注意点

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
			//此时改名成功
		}
这是最近遇到的几个问题,可能还有别的原因,欢迎交流





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值