深入了解File类

版权声明:转载需声明本人出品 https://blog.csdn.net/weixin_40288381/article/details/88594048

概述

java.io.file类即文件和目录名的抽象表示形式。Java将电脑中的文件和文件夹封装成了一个File类,我们可以使用File类对文件和文件夹进行操作

File下静态变量
//与系统有关的路径分隔符
//windos下为:分号
//linux下为:冒号
public static final char pathSeparatorChar = fs.getPathSeparator();
public static final String pathSeparator = "" + pathSeparatorChar;

//与系统有关的名称分隔符
//windows下为:反斜杠\
//linux下为:正斜杠/
public static final char separatorChar = fs.getSeparator();
public static final String separator = "" + separatorChar;

注意:

  1. 路径是不区分大小写的
  2. 路径中的文件名称分隔符windows使用反斜杠,但由于路径通过字符串的形式表示,而字符串下反斜杠为特殊字符,因此需要再加一个反斜杠作为转义字符,此时两个反斜杠代表一个普通的反斜杠

File的构造方法

File源码

  //pathname:字符串的路径名称
  //路径可以是文件结尾,也可以是文件夹结尾
  //路径可以是相对路径。也可以是绝对路径
  //路径可以是存在的,也可以是不存在的
  //创建File对象,只是把字符串路径封装为File对象,不考虑路径的真实情况
  public File(String pathname) {
        if (pathname == null) {
            throw new NullPointerException();
        }
        this.path = fs.normalize(pathname);
        this.prefixLength = fs.prefixLength(this.path);
    }

   //根据parent路径和child路径创建一个新的File实例
   public File(String parent, String child) {
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null) {
            if (parent.equals("")) {
                this.path = fs.resolve(fs.getDefaultParent(),
                                       fs.normalize(child));
            } else {
                this.path = fs.resolve(fs.normalize(parent),
                                       fs.normalize(child));
            }
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

   //根据parent抽象路径名和child路径名创建一个新的File实例
   //父路径为File类型,可以使用File的方法对父路径进行一些操作,再使用路径创建对象
   public File(File parent, String child) {
        if (child == null) {
            throw new NullPointerException();
        }
        if (parent != null) {
            if (parent.path.equals("")) {
                this.path = fs.resolve(fs.getDefaultParent(),
                                       fs.normalize(child));
            } else {
                this.path = fs.resolve(parent.path,
                                       fs.normalize(child));
            }
        } else {
            this.path = fs.normalize(child);
        }
        this.prefixLength = fs.prefixLength(this.path);
    }

测试

public static void main(String[] args) {
	String pathName = "D:\\test";
	File file1 = new File(pathName); 
	System.out.println(file1);//打印:D:\test
	
	File file2 = new File(pathName+"\\","test2");
	System.out.println(file2);//打印:D:\test\test2
	
	File file3 = new File(file1,"test3");
	System.out.println(file3);//打印:D:\test\test3
	}

获取File相关属性

//返回File的绝对路径字符串
public String getAbsolutePath()

//返回此File表示的文件或目录名称,获取的就是构造方法传递路径的结尾部分
public String getName()

//将此File转换为路径名字字符串
public String getPath()

//返回此File表示的文件长度
//文件夹没有大小概念,不能获取文件夹的大小
//如果构造方法给出的路径不存在,那么length返回0
public long length()

//判断此File表示的文件或文件夹是否存在
public boolean exists()

//判断此File表示的是否为目录
public boolean isDirectory()

//判断此File表示的是否为文件
public boolean isFile()

//创建由此File表示的目录
//创建文件的路径必须存在,否则会抛出异常
public boolean mkdir()

//创建由此File表示的多级目录
//创建文件的路径必须存在,否则会抛出异常
public boolean mkdirs()

//删除由此File表示的文件或目录
public boolean delete()

//当且仅当具有该名称的文件不存在时,创建一个新的文件
//此方法只能创建文件,不能创建文件夹
//创建文件的路径必须存在,否则会抛出异常
public boolean createNewFile()

获取File目录中的子文件和文件夹

//返回String数组
public String[] list()
//返回File数组
public String[] list(FilenameFilter filter)

测试

File[] fileList = file1.listFiles();
for(File item :fileList) {
    System.out.println(item.getName());
}
递归获取File当前目录下所有文件及文件夹

先创建用于测试的目录和文件

public static void main(String[] args) throws IOException {
		String pathName = "D:\\test";
		File file1 = new File(pathName);
	
		//创建文件夹
		File file4 = new File(file1,"test4");
		file4.mkdir();
		
		File file8 = new File(file1,"test5");
		file8.mkdir();
		
		File file5 = new File(file4,"123.txt");
		File file6 = new File(file4,"456.txt");
		File file7 = new File(file4,"789.java");
		File file9 = new File(file8,"abc.txt");
		File file10 =new File(file8,"def.java");
		
		//创建文件
		file5.createNewFile();
		file6.createNewFile();
		file7.createNewFile();
		file9.createNewFile();
		file10.createNewFile();											
	}
public static void getAllFile(File dir) {
		File[] files = dir.listFiles();
		for(File file : files) {
			//判断如果是目录则继续递归
			if(file.isDirectory()) {
				getAllFile(file);
			}else {
				System.out.println(file);
			}
			
		}
	}

D:\test\test4\123.txt
D:\test\test4\456.txt
D:\test\test4\789.java
D:\test\test5\abc.txt
D:\test\test5\def.java

通过使用过滤器获得目标文件

在File类中有两个和ListFiles重载的方法,方法的参数就是过滤器

 //FilenameFilter接口,实现此接口的类实例可以用过滤文件名
 public File[] listFiles(FilenameFilter filter) {
        String ss[] = list();
        if (ss == null) return null;
        ArrayList<File> files = new ArrayList<>();
        for (String s : ss)
            if ((filter == null) || filter.accept(this, s))
                files.add(new File(s, this));
        return files.toArray(new File[files.size()]);
    }

  //FileFilter接口,实现此接口的类实例可以用过滤文件
  public File[] listFiles(FileFilter filter) {
        String ss[] = list();
        if (ss == null) return null;
        ArrayList<File> files = new ArrayList<>();
        for (String s : ss) {
            File f = new File(s, this);
            if ((filter == null) || filter.accept(f))
                files.add(f);
        }
        return files.toArray(new File[files.size()]);
    }
public interface FileFilter {

  	//FileFilter和FilenameFilter接口中都只有一个accept方法,用于实现过滤细节,返回boolean
    boolean accept(File pathname);
}
使用匿名内部类创建过滤器实例
public static void getAllFile(File dir) {
		File[] files = dir.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				//当Filename为目录或者以.java为结尾则返回File数组
				return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
			}
		});
		for(File file : files) {
			if(file.isDirectory()) {
				getAllFile(file);
			}else {
				System.out.println(file);
			}
			
		}
	}
过滤中详情
  1. listFiles方法对构造方法中传入的目录进行遍历,获取目录中的文件/文件夹,将其封装为File对象
  2. listFiles方法调用过滤器的accept方法
  3. listFiles会将已经遍历得到的Filter对象,传递进accept。accept返回true,则将其放进File数组,否则丢弃

猜你喜欢

转载自blog.csdn.net/weixin_40288381/article/details/88594048