Java crazy handout reading and learning java IO stream File class learning and Practice

Posted by slak on Tue, 22 Feb 2022 12:39:14 +0100

java handout reading and learning File class

Near the beginning of school, facing the pressure of postgraduate entrance examination and learning, we can relearn the core knowledge in java io stream through java handout books to form our own system. On a deeper level, the time for later study is increasingly reduced and tense. Through reading and learning, we can better cultivate the ability of self-study and avoid the excessive dependence on tutorials. It can also better improve the efficiency of learning in the next semester. Improve your summary ability.

File class

File introduction

The file class is Java The files and directories under the IO package represent platform independent files and directories, that is, if you want to operate files and directories in the program, you can complete them through the file class. It is worth noting that both files and directories are operated by file. File can create, delete and rename files and directories, and file cannot access the file content itself. If you need to access the file content itself, you need to use input / output streams.

Through the analysis of the source code structure diagram, we can know that there is no default construction method in the File class. The File directory created by File must be specified through the URL.

The File class can use the File path string to create a File instance. The File path string can be either an absolute path or a relative path. By default, the system always interprets the relative path according to the user's working path.

Once the File object is created, you can call the method of the File object to access it. The File class provides many methods to operate files and directories. Some common methods are listed below.

Access file name related methods

In general engineering, the name of the later part of pojo's get/set method is called property, and the instance variable is called attribute

Variables in Java classes can be called field s


The following is the corresponding part of the field above the source code.




The following describes the corresponding methods of accessing files

  • String getName(): returns the File name or path name represented by this File object (if it is a path, it returns the last level sub path name)

  • String getPath(): returns the path name corresponding to this File object.

  • File getAbsoluteFile(): returns the file object corresponding to the absolute path corresponding to this file object.

  • String getAbsolutePath(): returns the absolute pathname corresponding to this File object.

  • String getParent(): returns the parent directory name of the directory (last level subdirectory) corresponding to this File object.

  • boolean renameTo(File newName): renames the File or directory corresponding to the File object. If the renaming is successful, it returns true; Otherwise, false is returned.

These methods related to accessing files are corresponding in the source code of File class. As shown in the figure above.

Methods related to document detection

  1. boolean exists(): judge whether the File or directory corresponding to the File object exists.
  2. boolean canWrite(): judge whether the File and directory corresponding to the File object are writable.
  3. boolean canRead(): judge whether the File and directory corresponding to the File object are readable.
  4. boolean isFile(): judge whether the File object corresponds to a File, not a directory.
  5. boolean isDirectory(): judge whether the File object corresponds to a directory rather than a File.
  6. boolean isAbsolute(): judge whether the File or directory corresponding to the File object is an absolute path.

Summary: the relevant methods of file detection are summarized as follows: judge the existence of the file, judge whether the file is readable and writable, and judge the type of the file

The methods in the figure above correspond to some commonly used methods in file detection.

Methods related to file operation

  • boolean createNewFile(): when the File corresponding to the File object does not exist, this method will create a new File specified by the File object. If the creation is successful, it returns true; Otherwise, false is returned.
  • boolean delete(): deletes the File or path corresponding to the File object.
  • static File createTempFile(String prefix, String
    suffix): create a temporary empty File in the default temporary File directory, and use the given prefix, system generated random number and given suffix as the File name. This is a static method that can be called directly through the File class. The prefix parameter must be at least 3 bytes long. It is recommended to use a short, meaningful string for the prefix, such as "hjb" or "mail". The suffix parameter can be null, in which case the default suffix ". tmp" will be used.

The operation methods related to files mainly involve the creation and deletion of files, which can be learned corresponding to the relevant methods of directories

Methods related to directory operation

  • boolean
    mkdir(): attempts to create a directory corresponding to a File object. If the creation is successful, it returns true; Otherwise, false is returned. When this method is called, the File object must correspond to a path, not a File.

  • String[] list(): lists all sub File names and pathnames of the File object, and returns a string array.

  • File[] listFiles(): lists all sub files and paths of the file object and returns the file array.

  • static File[] listRoots(): lists all root paths of the system. This is a static method that can be called directly through the File class

    These written methods belong to the common methods in the File class.

Actual operation of File class

Example 1: create a File object with the current path and obtain the File information

package com.dzu.cn;

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

/**
 * @Author ChenRuXu
 * @Date 2022/2/21 20:47
 * @Version 1.0
 */
public class TestFile {
    public static void main(String[] args) throws IOException {
        File file = new File("file");
        System.out.println(file.getName());
        //Get absolute path
        System.out.println(file.getAbsolutePath());
        //Gets the parent path of the relative path
        System.out.println(file.getParent());
        //Get the upper level path
        System.out.println(file.getAbsoluteFile().getParent());
    }
}

Example 2: creating files

Method 1: create a file according to the file path

package com.dzu.cn;

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

/**
 * @Author ChenRuXu
 * @Date 2022/2/22 17:34
 * @Version 1.0
 */
public class CreateFile {
    public static void main(String[] args) {
        CreateFile createFile = new CreateFile();
        createFile.create01();
    }

    //Create a file based on the path of the file
    public void create01(){
        String filePath ="e:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("File created successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Method 2: parent File plus child path to build File

//Build a file (file part, string child) according to the parent file plus the child path
    public void create02()  {
        //The parent file is saved in memory
        File partentFile = new File("e:\\");
        String filename = "news2.txt";
        File file = new File(partentFile,filename);
        try {
            file.createNewFile();
            System.out.println("Created successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


Method 3: create parent path plus child path

//Creation method 3
    public void create03(){
        String partentpath = "e:\\";
        String fileName = "news3.txt";
        File file = new File(partentpath,fileName);
        try {
            file.createNewFile();
            System.out.println("File 3 created successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


According to the three ways of creating files, there are three constructors in the File class.

Example 3: obtain relevant information of documents

package com.dzu.cn;

import java.io.File;

/**
 * Get file information
 * @Author ChenRuXu
 * @Date 2022/2/22 18:18
 * @Version 1.0
 */
public class FileInformation {
    public static void main(String[] args) {
        //Create file object
        File file = new File("e:\\news1.txt");
        //Call relevant methods to obtain file information (file name)
        System.out.println(file.getName());
        //Get file parent directory
        System.out.println(file.getParent());
        //Get the file size in bytes (three bytes for one Chinese character)
        System.out.println(file.length());
        //Determine whether the file exists
        System.out.println(file.exists());
        //Determine whether it is a file
        System.out.println(file.isFile());
        //Determine whether the file is a directory
        System.out.println(file.isDirectory());
        
    }
}

Example 4: Directory related operations

Create a first level directory, create a multi-level directory, and delete a directory

Operation 1: determine whether the file exists and delete it

package com.dzu.cn;

import java.io.File;

/**
 * Directory related operations
 * @Author ChenRuXu
 * @Date 2022/2/22 18:34
 * @Version 1.0
 */
public class Directory {
    public static void main(String[] args) {
        Directory directory = new Directory();
        directory.m1();
    }

    /**
     * Delete file
     */
    public void m1(){
        String filepath = "e:\\news1.txt";
        File file = new File(filepath);
        if (file.exists()){
            if (file.delete()){
                System.out.println("File deleted successfully");
            }else {
                System.out.println("File deletion failed");
            }
        }else {
            System.out.println("file does not exist");
        }
    }
}


Operation 2: create a new demo folder directory under disk D, and randomly create several files under the directory for testing

After testing, it can be found that when there are other things in the file, the deletion will fail, and if it is empty, the deletion will succeed

/**
     * remove folders
     */
    public void m2(){
        String filepath ="d:\\demo";
        File file = new File(filepath);
        if (file.exists()){
            if (file.delete()){
                System.out.println("Folder deleted successfully");
            }else {
                System.out.println("Folder deletion failed");
            }
        }else {
            System.out.println("Folder does not exist");
        }
    }

Operation 3: create multi-level directory (mkdirs)

public void m3(){
        String filepath ="d:\\demo\\aa\\bb";
        File file = new File(filepath);
        if (file.exists()){
            System.out.println("File exists");
        }else {
            if (file.mkdirs()){
                System.out.println("Multi level directory created successfully");
            }else {
                System.out.println("Failed to create multi-level directory");
            }
        }

    }

summary

Macro operation of documents. It is a foundation for us to write and thoroughly understand the upload and download of springboot files, and it is also the pre knowledge for us to practice file upload and download again later.

Topics: Java