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

时间:2022-12-10 00:00:34
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();