java之File对象对文件的操作常用的几个方法

java之File对象对文件的操作常用的几个方法


File对象是对文件操作最常用的类,平常工作总用的很多,贴出来了几个我工作常用的几个方法。简单总结了下
直接上代码:

//构建文件对象
		File file=new File("E:/android_demo/a");
		File fileTest=new File("E:/android_demo/a/test.mp3");
		
		//获取文件的父路径
		File f=file.getParentFile();
		System.out.println("f=="+f);//E:\android_demo
		
		//判断文件是否存在
		boolean is=file.exists();//不存在,返回fasle
		System.out.println("is=="+is);
		
		//获取文件的绝对路径可以理解等同getPath
		String path1=file.getAbsolutePath();
		System.out.println("path=="+path1);//E:\android_demo\a
		
		//获取文件的路径
		String path2=file.getPath();
		System.out.println("path2=="+path2);//E:\android_demo\a
		
		//获取当前文件名
		String s=file.getName();
		System.out.println("s==="+s);
		
		//创建一个文件夹,即:E:/android_demo/a
		file.mkdir();
		
		//创建一个文件,即:E:/android_demo/a/test.mp3
		
		fileTest.createNewFile();
		//文件大小,文件存储时占用的字节数;
		long l=f.length();
		System.out.println("l=="+l);
		
		//获取文件路径string
		String str=fileTest.toString();
		System.out.println("str=="+str);// E:\android_demo\a\test.mp3
		
		//给文件重新命名
		File fileTest2=new File("E:/android_demo/a/test2.mp3");
		boolean b2=fileTest.renameTo(fileTest2);
		System.out.println("b2=="+b2);// E:/android_demo/a/test2.mp3
		
		//删除文件
		boolean b3=fileTest.delete();
		
		//删除文件夹,注意删除的文件夹下面必须没有文件才可以删除,有的话要便利删除所有文件,然后才删除
		boolean b4=file.delete();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值