Take you to the File class in Java

Posted by kelseyirene on Wed, 02 Mar 2022 23:07:18 +0100

summary

To learn the File class in Java, first of all, we need to know that the definition of File class in Java API, that is, the abstract representation of File and directory path, is not the File itself. Therefore, in the File class, the operations involved are only about the File name and directory path, not the File content. If you want to operate the File content, you need to learn the I/O flow (input / output flow).

Construction method

Basic introduction

Only when the File class is constructed can we operate on it later. For the construction of File class, the following three methods are introduced:
Pathnames of abstractly represented files and directories:

  • public File(String pathname): create a new File instance by converting the given pathname string to an abstract pathname.
  • public File(String parent, String child): creates a new File instance from the parent pathname string and the child pathname string.
  • public File(File parent, String child): creates a new File instance from the parent abstract pathname and child pathname strings.

The first one uses more and the latter two use less

Code example

import java.io.File;

public class FileDemo1 {
    public static void main(String[] args) {

        //public File(String pathname)
        String pathname1 = "F:\\test1.txt";
        File file1 = new File(pathname1);

        //public File(String pathname)
        String pathname2 = "F:\\test2\\test1.txt";
        File file2 = new File(pathname2);

        //Less use below

        //public File(String parent, String child)
        String parent = "F:\\test3";
        String child = "test1.txt";
        File file3 = new File(parent,child);

        //public File(File parent, String child)
        File parentDir = new File("F:\\test");
        String child1 = "test2.txt";
        File file4 = new File(parentDir,child1);
        
    }
}

common method

The operation of File class is still very important, so there are many common methods. In order to facilitate memory, I divide it into:

  • Get basic information about files and directories
  • Judgment function
  • Create and delete functions
  • Directory traversal function

These methods are introduced and illustrated with examples

Get basic information about files and directories

  • public String getName(): returns the name of the File or directory represented by this File.
  • public String getPath(): converts this File to a pathname string.
  • public String getParent(): get parent path
  • public String getAbsolutePath(): returns the absolute pathname string of this File

Code example

import java.io.File;

public class FileDemo2 {
    public static void main(String[] args) {

        File file = new File("F:\\test1\\test2\\text.txt");

        //Convert this File to a pathname string.
        System.out.println("File path:"+ file.getPath());
        //Returns the name of the File or directory represented by this File
        System.out.println("File name:"+ file.getName());
        //Get parent path
        System.out.println("Get parent path"+ file.getParent());
        //Returns the absolute pathname string of this File
        System.out.println("Absolute path name" + file.getAbsolutePath());
    }
}

Judgment function

  • public boolean exists(): whether the File or directory represented by this File actually exists.
  • public boolean isDirectory(): this File indicates whether it is a directory.
  • public boolean isFile(): this File indicates whether it is a File.
  • public isAbsolute(): judge whether the File or directory corresponding to the File object is an absolute path
  • public boolean canRead(): judge whether the File or directory corresponding to the File object is readable
    public boolean canWrite(): judge whether the File or directory corresponding to the File object is writable
  • public boolean isHidden(): judge whether the File or directory corresponding to the File object is hidden

If the file or directory does not exist, exists(), isFile(), and isDirectory() return true

Code example

import java.io.File;

public class FileDemo3 {

    public static void main(String[] args) {
        File file1 = new File("F:\\test\\test1\\test2.txt");
        File file2 = new File("F:\\test");

        //Does the File or directory represented by this File actually exist
        boolean exists1 = file1.exists();
        boolean exists2 = file2.exists();
        System.out.println(exists1);
        System.out.println(exists2);

        //Is this File a directory
        boolean directory1 = file1.isDirectory();
        boolean directory2 = file2.isDirectory();
        System.out.println(directory1);
        System.out.println(directory2);

        //This File indicates whether it is a File
        boolean file1File = file1.isFile();
        boolean file2File = file2.isFile();
        System.out.println(file1File);
        System.out.println(file2File);

        //Judge whether the File or directory corresponding to the File object is an absolute path
        boolean absolute = file1.isAbsolute();
        System.out.println(absolute);

        //Judge whether the File or directory corresponding to the File object is readable
        boolean canRead = file1.canRead();
        System.out.println(canRead);

        //Judge whether the File or directory corresponding to the File object is writable
        boolean canWrite = file1.canWrite();
        System.out.println(canWrite);

        //Judge whether the File or directory corresponding to the File object is hidden
        boolean hidden = file2.isHidden();
        System.out.println(hidden);
    }
}

Create and delete functions

  • public boolean createNewFile(): creates a new empty file if and only if the file with this name does not exist yet.
  • public boolean delete(): delete the File or directory represented by this File. Only empty directories can be deleted.
  • public boolean mkdir(): create the directory represented by this File.
  • public boolean mkdirs(): create the directory represented by this File, including any required but nonexistent parent directory

API Description: delete method. If this File represents a directory, the directory must be empty to delete.

Code example

import java.io.File;
import java.io.IOException;

public class FileDemo4 {
    public static void main(String[] args) throws IOException {
        //create a file
        File file1 = new File("test.txt");
        System.out.println("Does it exist:"+ file1.exists());//false
        System.out.println("Create"+ file1.createNewFile());//An exception needs to be thrown
        System.out.println("Is there:"+ file1.exists()); //true

        //Create directory (single)
        File file2 = new File("F:\\test");
        System.out.println("Does it exist:"+ file2.exists());//false
        System.out.println("Create"+ file2.mkdir());
        System.out.println("Is there:"+ file2.exists()); //true

        //Create multi-level directory
        File file3 = new File("F:\\test1\\test2");
        System.out.println("Does it exist:"+ file3.exists());//false
        System.out.println("Create"+ file3.mkdirs());
        System.out.println("Is there:"+ file3.exists()); //true

        //Deletion of files
        System.out.println(file1.delete());

        //Deletion of directory
        System.out.println(file2.delete());
        System.out.println(file3.delete());//Only one level can be deleted

    }
}

Directory traversal function

  • public String[] list(): returns a String array representing all sub files or directories in the File directory
  • public File[] listFiles(): returns a File array representing all sub files or directories in the File directory

The File object that calls the listFiles method must represent the actual directory, otherwise it returns null and cannot be traversed.

Code example

import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class FileDemo5 {
    public static void main(String[] args) {
        File dir = new File("F:\\test");
        dir.mkdirs();
        System.out.println(dir.exists());
        //File dir1 = new File("F:\\test");

        //Get the names of files and folders in the current directory
        String[] names = dir.list();
        //ergodic
        for(String name : names){
            System.out.println(name);
        }

        //Get the files and folder objects in the current directory. As long as you get the file objects, you can get more information
        File[] files = dir.listFiles();
        for(File file : files){
            System.out.println(file);
        }
    }
}

But for the traversal of multi-level directories, we need to use recursive methods

/*
Printing of multi-level directory. Before traversing, there is no way to know how many levels of directories there are, so we can use recursive implementation
 */

import java.io.File;

public class FileDemo6 {
    public static void main(String[] args) {
        File dir = new File("F:\\test1");
        listSubFiles(dir);

    }

    private static void listSubFiles(File dir) {
        if(dir != null && dir.isDirectory()){
            File[] listFiles = dir.listFiles();
            if(dir != null){
                for(File sub : listFiles){
                    listSubFiles(sub);//Recursive call
                }
            }
        }
        System.out.println(dir);
    }
}

Topics: Java