【JavaEE】File operations

Insert image description here

Preface

Files are widely used in our daily lives. We cannot use any program without file operations. This file not only refers to files that can be seen in daily life, but even our keyboard and screen can be regarded as a file. We can see the importance of file operations, so today I will share with you about Java file operations.
Insert image description here

what is a file

Let’s first understand files in a narrow sense. For persistent storage I/O devices such as hard disks, when we want to save data, it is often not saved as a whole, but as independent units. This independent unit is abstracted into a file. Concepts are like real documents on your desk.

In addition to data content, files also have some information, such as file name, file type, file size, etc., which do not exist as file data. We regard this part of information as meta-information of the file.
Insert image description here
Insert image description here

Tree structure organization and directory

In Linux, the file system is organized in a tree structure, also called a hierarchical directory structure. The entire file system has only one root directory (/), and all files and directories are organized and managed starting from the root directory. There can be multiple subdirectories under the root directory, and each subdirectory can contain other subdirectories and files, thus forming a tree structure.

Directories are containers used to organize and store files, and can also be understood as folders. Directories can contain other directories and files, forming a tree structure. In Linux, all directories and files can be uniquely identified and searched through paths. The path is the complete path from the root directory to the specific file or directory. For example, the path "/home/user/Documents/file.txt" means starting from the root directory, entering the home directory, then entering the user directory, then entering the Documents directory, and finally finding the file named file.txt.

Windows' file system also uses a similar tree structure, called a folder tree. Each disk partition or drive has its own root directory, called the root folder. There can be multiple subfolders under the root folder, and each subfolder can contain other subfolders and files, forming a tree structure.

Insert image description here

file path

A file path refers to the complete path from the root directory to a specific file or directory in the computer file system. A file path is used to uniquely identify and find a file or directory.

In Linux, file paths are separated by slashes (/), starting from the root directory and going to the specific file or directory. For example, the path "/home/user/Documents/file.txt" means starting from the root directory, entering the home directory, then entering the user directory, then entering the Documents directory, and finally finding the file named file.txt.

In Windows, file paths are separated by backslash (\) or forward slash (/), starting from the root folder and going to the specific file or folder. For example, the path "C:\Users\UserName\Documents\file.txt" means starting from the root folder of the C drive, entering the Users folder, then entering the UserName folder, then entering the Documents folder, and finally finding the file named file.txt document.

\Although and can be used /as delimiters under Windows , we are still accustomed to using them /because \escaping operations are required in some cases.

File paths can be divided into absolute paths and relative paths.

  • An absolute path is the complete path starting from the root directory or root folder to a specific file or directory
  • A relative path is a path starting from the current working directory to a specific file or directory.

For example, in Linux, if the current working directory is "/home/user", then the relative path "Documents/file.txt" means entering the Documents directory and finding the file named file.txt. The absolute path of this file is "/ home/user/Documents/file.txt".

. represents the current directory, . . represents the upper-level directory of the current directory

file type

Even ordinary files are often divided into different types according to the different data they save. We generally simply divide them into text files and binary files, which respectively refer to text that is encoded by the character set and non-standard files that are saved in a standard format. Files that are character set encoded.

Text files and binary files are two common file types in computers. They differ in encoding, storage, and uses.

  • Encoding method: Text files are files based on character encoding. Common encodings include ASCII encoding, UNICODE encoding, etc. Binary files are files based on value encoding, consisting of binary digits 0 and 1, and there is no unified character encoding.
  • Storage method: Text files use fixed-length encoding, and each character occupies a fixed number of bits, usually 8 bits or 16 bits. Binary files use variable-length encoding and are composed of a set of binary digits 0 and 1. The number of bits representing a value is determined by the specific application.
  • Purpose: Text files are mainly used to store and process text data, such as text editing, typesetting, program source code, etc. Binary files are mainly used to store and process binary data, such as images, audio, videos, executable files, etc.
  • File extension: The extension of text files is generally .txt, .doc, .docx, etc., while the extension of binary files depends on the specific file type, such as .jpg, .mp3, .avi, etc.

So how should we usually judge whether a certain file is a text file or a binary file? Let me teach you a simple method: Don’t we have Notepad on our computers? Open this file in the form of Notepad. If no garbled characters appear after opening, it is a text file. If garbled characters appear, it means that the file is a binary file. .

Insert image description here

This is a binary file.

Insert image description here
This is a text file.

File Permissions

File permissions refer to the access rights to files and directories in the computer file system. By setting permissions on files, you can achieve the following three access restrictions:

  1. Allow only users to access;
  2. Allow access to users in a pre-specified user group;
  3. Allow access to any user on the system.

In Linux, file permissions are divided into three types: read, write, and execute, represented by the letters r, w, and x respectively. Each file or directory has three sets of permissions, corresponding to the file owner, users in the same group, and other users. For example, setting permissions to "-rwx r-- r–" means that the file owner has read, write, and execute permissions, while users in the same group and other users only have read permissions.

In Windows, file permissions are divided into four types: read, write, read and execute, and modify, represented by the letters R, W, RX, and M respectively. Each file or folder has a set of permissions that can be set for different users or user groups. For example, permissions set to "Read and Execute" means that the user or group can read and execute the file, but not write or modify it.

Insert image description here

File operations in Java

To operate files in Java, you need to use java.io.Filemethods in the class to operate.

Common properties of the File class

Insert image description here
These two attributes are used to represent the system's path separator.

Common construction methods of File class

Insert image description here

File(File parent, Stringchild) Create a new File instance based on the parent directory + child file path
File(String pathname) Create a new File instance based on the file path. The path can be an absolute path or a relative path.
File(String parent, Stringchild) Create a new File instance based on the parent directory + child file path. The parent directory is represented by a path.

Among these common construction methods, the second method of directly specifying the path is more commonly used.

Common methods of File class

Modifiers and return value types method signature illustrate
String getParent() Returns the parent directory file path of the File object
String getName() Returns the plain file name of the FIle object
String getPath() Returns the file path of the File object
String getAbsolutePath() Returns the absolute path of the File object
String getCanonicalPath() Returns the modified absolute path of the File object
boolean exists() Determine whether the file described by the File object actually exists
boolean isDirectory() Determine whether the file represented by the File object is a directory
boolean isFile() Determine whether the file represented by the File object is an ordinary file
boolean createNewFile() Based on the File object, an empty file is automatically created. Returns true after successful creation
boolean delete() Based on the File object, delete the file. Returns true after successful deletion
void deleteOnExit() According to the File object, the annotated file will be deleted, and the deletion will not be performed until the end of the JVM run.
String[] list() Returns all file names in the directory represented by the File object
File[] listFiles() Returns all files in the directory represented by the File object, represented by a File object
boolean mkdir() Create the directory represented by the File object
boolean mkdirs() Creates the directory represented by the File object and, if necessary, creates intermediate directories
boolean renameTo(File dest) Renaming files can also be regarded as our usual cut and paste operations.
boolean canRead() Determine whether the user has readable permissions on the file
boolean canWrite() Determine whether the user has writable permissions on the file

Example one:

public class Test {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file = new File("d:/test.txt");
        System.out.println(file.getParent());
        System.out.println(file.getName());
        System.out.println(file.getPath());
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getCanonicalPath());
    }
}

Insert image description here

Drive letters are not case sensitive

Example two:

public class Test2 {
    
    
    public static void main(String[] args) {
    
    
        File file = new File("d:/test.txt");
        System.out.println(file.exists());  //false
        System.out.println(file.isDirectory());  //false
        System.out.println(file.isFile());  //false
    }
}

When creating a File object, if the file does not exist, the file will not be automatically created.

public class Test2 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file = new File("d:/test.txt");
        System.out.println(file.exists());  //false
        System.out.println(file.isDirectory());  //false
        System.out.println(file.isFile());  //false

        //如果文件创建成功则返回true,创建失败返回false
        boolean ret = file.createNewFile();
        System.out.println(ret);  //true
        System.out.println(file.exists());  //true
        System.out.println(file.isDirectory());  //false
        System.out.println(file.isFile());  //true

        //如果删除文件成功,则返回true,删除失败则返回false
        ret = file.delete();
        System.out.println(ret);  //true
        System.out.println(file.exists());  //false
    }
}

Example three:

public class Test3 {
    
    
    public static void main(String[] args) throws IOException, InterruptedException {
    
    
        File file = new File("d:/test1.txt");
        boolean ret = file.createNewFile();
        System.out.println(ret);
        file.deleteOnExit();
        //让程序等待30秒再结束
        Thread.sleep(30000);
    }
}

When using deleteOnExit(0the method, the file will not be deleted immediately, but will be deleted when the JVM is finished.

Insert image description here
Insert image description here
When the program ends, the test1.txt file is deleted.

Insert image description here
Insert image description here

Example four:

public class Test4 {
    
    
    public static void main(String[] args) {
    
    
        File file = new File("D:/code/this-is-my-java-ee-learning");
        //list() 方法以字符串的形式返回指定目录下的所有文件夹/文件的名称
        String[] str = file.list();
        System.out.println(Arrays.toString(str));
    }
}

Insert image description here

Example five:

public class Test5 {
    
    
    public static void main(String[] args) {
    
    
        File file = new File("D:/code/this-is-my-java-ee-learning");
        //listFiles() 方法以File对象的形式返回指定目录下的文件夹/文件的
        File[] files = file.listFiles();
        for (File f : files) {
    
    
            System.out.println(f.getName());
        }
    }
}

Insert image description here

Example six:

public class Test6 {
    
    
    public static void main(String[] args) {
    
    
        File file = new File("d:/aaa");
        //mkdir() 方法创建目录
        boolean ret = file.mkdir();
        System.out.println(ret);
    }
}

Insert image description here
Insert image description here

The mkdir() method can only create one-level directories, but cannot create multi-level directories.

public class Test6 {
    
    
    public static void main(String[] args) {
    
    
        File file = new File("d:/aaa/bbb/ccc");
        boolean ret = file.mkdir();
        System.out.println(ret);
    }
}

Insert image description here

To create a multi-level directory, you need to use mkdirs()the method.

public class Test6 {
    
    
    public static void main(String[] args) {
    
    
        File file = new File("d:/aaa/bbb/ccc");
        boolean ret = file.mkdirs();
        System.out.println(ret);
    }
}

Insert image description here
Insert image description here

Example seven:

public class Test7 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File src = new File("d:/test.txt");
        boolean ret = src.createNewFile();
        System.out.println(ret);
        File des = new File("d:/test1.txt");
        ret = src.renameTo(des);
        System.out.println(ret);
    }
}

Insert image description here
Insert image description here

Example eight:

public class Test8 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file = new File("d:/test.txt");
        boolean ret = file.createNewFile();
        System.out.println(file.canRead());  //true
        System.out.println(file.canWrite());  //true
    }
}

Insert image description here

Guess you like

Origin blog.csdn.net/m0_73888323/article/details/133553172