FIle
- 文件 file
- 目录 directory
- 路径 path
FIle类的构造函数与差异
-
File(String pathname)
通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。 -
File(String parent, String child)
根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
public static void func1() throws IOException {
// 通过字符串创建文件对象
File file=new File("D://a.txt");
boolean newFile = file.createNewFile();
System.out.println(newFile);
}
public static void func2() throws IOException {
// 通过字符串创建文件对象
File file=new File("D://123","abc.txt");
boolean newFile = file.createNewFile();
System.out.println(newFile);
}
public static void func3() throws IOException {
// 通过字符串创建文件对象
File parent=new File("D://1234");
if (!parent.exists()){
parent.createNewFile();
}
File file=new File(parent,"abc.txt");
boolean newFile = file.createNewFile();
System.out.println(newFile);
}
创建文件与文件夹
file.createNewFile() //创建文件
mkdir()创建文件夹
mkdirs()创建多层文件夹
delete()删除文件或目录
length()获取文件的字节数
isDirectory()判断是否为文件夹
isFile()判断是否为文件
文件过滤器接口
- FileFilter
通过文件对象设置过滤规则,例如是否文件/目录 - FilenameFilter
通过重写accept(File dir, String name) 方法实现过滤规则,例如name.endWidth(".txt")【以txt结尾的文件】
public class MyFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
}
public class MyFIleNameFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return name.contains("abc");
}
}
// 获取文件夹下指定后缀的文件
public static void getAppointedFile(){
FilenameFilter filenameFilter=new MyFIleNameFilter();
File file=new File("d://123");
File[] files = file.listFiles(filenameFilter);
for(File temp:files){
System.out.println(temp);
}
}
// 根据目录下是否是文件过滤文件
public static void getIsFile(){
FileFilter fileFilter=new MyFileFilter();
File dir=new File("d://123");
File[] files = dir.listFiles(fileFilter);
for(File file:files)
System.out.println(file);
}