Detailed Java-based File class

 

Detailed Java-based File class

Construction method

Main member method

How to get features 

Method of judging function

How to create delete function

Directory traversal

Case-File Search

Case-file search (advanced gameplay)

Creation is not easy, if this blog is helpful to you, please remember to leave a message + like it.


The Java.io.File class is an abstract representation of file and directory path names , and is mainly used for operations such as file and directory creation, search, and deletion. Instances of the File class are immutable; that is, once created, the abstract path name represented by the File object will never change.

There are three important words to remember: file (file), directory (folder), path (path)

Construction method

Construction method summary

File(File parent, String child)

          Create a new File instance based on the parent abstract path name and child path name string.

File(String pathname)

          Create a new File instance by converting the given pathname string into an abstract pathname.

File(String parent, String child)

          Create a new File instance based on the parent path name string and the child path name string.

//File类的构造函数--练习
private static void show02(){
     File file= new File("F:\\04Java\\19java","Hello.java");
     System.out.println(file);
}

private static void show01(){
   File f1= new File("F:\\04Java\\19java");
   System.out.println(f1);//重写了ToString()方法

   File f3= new File("b.txt");
   System.out.println(f3);
}
private static void show03(){
     File file=new File("F:\\04Java\\19ava");
     File newFile = new File(file,"Hello.java");
     System.out.println(newFile);
}

Main member method

Method of obtaining 

Method summary
 String getAbsolutePath()
          Returns the absolute pathname string of this abstract pathname.
 String getName()
          Returns the name of the file or directory represented by this abstract pathname.
 String getPath()
          Convert this abstract pathname into a pathname string.
 long length()
          Returns the length of the file represented by this abstract pathname.
//获取文件绝对路径
private static void show04() {
     File file=new File("F:\\04Java\\19java");
     File absoluteFile=file.getAbsoluteFile();//返回File对象的绝对路径
     System.out.println(absoluteFile);
     File file2=new File("a.txt");
     File absoluteFile2=file2.getAbsoluteFile();//返回File对象的绝对路径
     System.out.println(absoluteFile2);
     System.out.println("____________________________");
}
//file1.getName()  获取最后一个路径名
private static void show02(){
     File file=new File("F:\\04Java\\19java");
     String name=file.getName();//最后的路径名
     System.out.println(name);

     File file1=new File("F:\\04Java\\19java\\小小张自由");
     String name1=file1.getName();//最后的路径名
     System.out.println(name1);
}
//file.getPath()  构造函数中传递什么值,就返回什么值
private static void show01(){
     File file=new File("F:\\04Java\\19java");
     String path=file.getPath();//传递的参数是什么,返回值就是什么
     System.out.println(path);
     File file1=new File("b.txt");
     String path1=file1.getPath();
     System.out.println(path1);
}
 //file.length() 获取文件的大小
private static void show03(){
     File file=new File("F:\\迅雷下载\\AirtestIDE-win-1.2.6.zip");
     long length=file.length();//文件名的大小,路径错误则为0
     System.out.println(length);//单位字节
}

Judgment method

Method summary
 boolean exists()
          Test whether the file or directory represented by this abstract pathname exists
 boolean isDirectory()
          Test whether the file represented by this abstract pathname is a directory.
 boolean isFile()
          Test whether the file indicated by this abstract pathname is a standard file.
//用于判断构造函数中给定的路径是否为目录、文件
public static void main(String[] args){
	File file = new File("F:\\04Java\\19java");
	System.out.println(file.exists());//判断文件名是否存在
	System.out.println(file.isDirectory());//判断是否以文件夹结尾
	System.out.println(file.isFile());//判断是否以文件结尾
}

Create and delete methods

Method summary
 boolean createNewFile()
          If and only if there is no file with the name specified by this abstract path name, a new empty file is created indivisible.
 boolean delete()
          Delete the file or directory indicated by this abstract pathname.
 boolean mkdir()
          Create the directory specified by this abstract pathname.
 boolean mkdirs()
          Create the directory specified by this abstract pathname, including all necessary but non-existent parent directories.
//File类中CreateNewFile()方法只能新建文件,创建成功true
private static void show01()throws IOException{
    File file=new File("F:\\04Java\\19java\\99.txt");
    boolean newFile=file.createNewFile();//只能新建文件,创建成功true
    System.out.println(newFile);
}
//File类中Delete()方法
private static void show03(){
    File file=new File("F:\\04Java\\19java\\HelloJava");
    boolean delete=file.delete();//可以删除文件夹只能是空文件夹
    System.out.println(delete);

    File file1=new File("F:\\04Java\\19java\\99.txt");
    boolean delete1=file1.delete();//可以删除文件
    System.out.println(delete1);
    }
//File类中mkdir()和mkdirs()的方法创建单级、多级目录
private static void show02(){
    File file=new File("F:\\04Java\\19java\\HelloJava");
    boolean mkdir=file.mkdir();//创建单级目录
    System.out.println(mkdir);
    File file1=new File("F:\\04Java\\19java\\Hello\\Java");
    boolean mkdirs=file1.mkdirs();//创建多级目录
    System.out.println(mkdirs);
}

 Directory traversal

Method summary
 String[] list()
          Returns an array of strings that specify the files and directories in the directory represented by this abstract pathname.
 File[] listFiles()
          Returns an array of abstract pathnames that represent the files in the directory indicated by this abstract pathname.
//file.listFiles();方法返回值是一个File[]
private static void show02(){
    File file=new File("F:\\04Java\\19java");
    File[]files=file.listFiles();
    for(File file1:files){
        System.out.println(file1);
    }
}

//file.list();方法返回值是一个String[]
private static void show01(){
    File file=new File("F:\\04Java\\19java");
    String[] list=file.list();
    System.out.println(list);//地址值
    for(String i:list){
        System.out.println(i);
    }
}

Case-File Search

     1. Search for files with the extension .pdf

     2. Directory search, can not judge how many levels of directories, so use recursion to traverse all directories.

     3. When traversing the directory, the obtained sub-files are judged whether they meet the conditions by the file name.

public class DiGuiDemo3 { 
    public static void main(String[] args) {
        // 创建File对象 
        File dir = new File("E:\\书籍"); 
        // 调用打印目录方法 
        printDir(dir); 
    }
    public static void printDir(File dir) { 
        // 获取子文件和目录 
        File[] files = dir.listFiles(); 
        
        // 循环打印 
        for (File file : files) { 
            if (file.isFile()) { 
                // 是文件,判断文件名并输出文件绝对路径 
                if (file.getName().endsWith(".PDF")) {
                    System.out.println("文件名:" + file.getAbsolutePath());
                }
            }else{ 
                // 是目录,继续遍历,形成递归 
                printDir(file); 
            } 
        } 
    } 
}

Case-file search (advanced gameplay)

  Use FileFilter interface or FilenameFilter interface, it is File filter . The parameters of this interface method are objects of the FIle class. There is only one method in the interface.

//Sun公司封装的两个文件过滤的接口
public interface FilenameFilter {
    boolean accept(File dir, String name);
}
public interface FileFilter {
    boolean accept(File pathname);
}

The file search function can be realized in any of the following ways: the first method uses the  FileFilter interface, and the second method uses the FilenameFilter interface.

One of the following three ways of playing uses the implementation class of the interface , one uses the Lambda expression , and the other uses the anonymous inner class

public static void main(String[] args) {
    File file=new File("E:\\书籍");
    //System.out.println(file);
    getAllFile(file);
}
//以下是三种玩法
public static void getAllFile(File file) {

   //方式一、使用FIleFilter接口的实现类
   File[] files = file.listFiles(new Demo09FileFilterImpl());//实现了FIleFilter接口
   //方式1. 使用Lambda表达式
   File[] files = file.listFiles((pathname)->{
         return pathname.getName().toLowerCase().endsWith(".pdf");//
   });

   //方式二、使用FilenameFilter
   File[] files =file.listFiles(new FilenameFilter() {
        @Override     //两个路径
        public boolean accept(File dir, String name) {
            return new File(dir,name).isDirectory()|| name.toLowerCase().endsWith("pdf");
         }
     });
}

创作不易,如果本篇博客对您有一定的帮助,大家记得留言+点赞哦。

 

 

 

Guess you like

Origin blog.csdn.net/promsing/article/details/112832380