Java file basic operation

1, Introduction

  java. io. The file class is an abstract representation of file and directory pathnames. File is a basic class of Java in the whole file IO system. It can perform operations on files, folders and paths, such as creating files or folders, obtaining paths and details, judging whether files exist, deleting, renaming, and obtaining files or folders in the current directory.

  • File class is a system independent class. Any operating system can use the methods in this class
  • File is an abstract representation of file and directory path names, that is, the object of file class represents the path of a file or a directory (folder), not the file itself
  • The File class cannot directly access the File content itself. If you need to access the File content itself, you need to use the input / output stream

Path considerations

  1. The path is not case sensitive, there is (..) in the path Indicates the upper level directory. If the path name starts with a slash (/), it means to navigate from the "root directory".

  2. The file name separator in the path window uses the backslash (\) and also supports the backslash (/). Other platforms (Linux, Android, IOS, etc.) use the backslash as the separator (/). The "\" in the Java program represents the escape character, so it needs to use "\" or "/" to represent the path in Windows. It is recommended to use file in the actual encoding process The separator is represented by a constant value, which can be cross platform.

2, Construction method

2.1 File(String pathName)

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

    /**
     * Create a new File instance by converting the given pathname string to an abstract pathname
     */
    @Test
    public void constructOne() {
        //The path can be the end of a folder
        File fileOne = new File("C:\\myFile\\example\\");
        //The path can be the end of the file
        File fileTwo = new File("C:\\myFile\\example\\create.txt");
        //The path can be a path that does not exist
        File fileThree = new File("C:\\myFile\\example\\xxxxx\\xxx");
        //The path can be relative
        File fileFour = new File("..\\example\\");
        System.out.println("The path can be the end of a folder:" + fileOne);
        System.out.println("The path can be the end of the file:" + fileTwo);
        System.out.println("The path can be a path that does not exist:" + fileThree);
        System.out.println("The path can be relative:" + fileFour);
    }

Operation results:

The path can be the end of a folder: C:\myFile\example
 The path can be the end of the file: C:\myFile\example\create.txt
 The path can be a path that does not exist: C:\myFile\example\xxxxx\xxx
 The path can be relative:..\example

2.2 File(String parent, String child)

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

    /**
     * Create a new File instance based on the parent pathname string and the child pathname string
     */
    @Test
    public void constructTwo() {
        //Parent path string, child path string
        File file = new File("C:\\myFile\\example\\","constructTwo.txt");
        System.out.println("Create from pathname string and pathname string File: " + file);
    }

Operation results:

Create from pathname string and pathname string File: C:\myFile\example\constructTwo.txt

2.3 File(File parent, String child)

Create a new File instance with the given parent abstract pathname and child pathname string.

    /**
     * Create a new File instance with the given parent abstract pathname and child pathname string
     */
    @Test
    public void constructThree() {
        File parentFile = new File("C:\\myFile\\example\\");
        //Parent abstract pathname, child path string
        File fileOne = new File(parentFile, "constructThree.txt");
        System.out.println("Creates a new path from the parent abstract pathname and child pathname strings File(Subpath without folder): " + fileOne);
        File fileTwo = new File(parentFile, "xxx\\constructThree.txt");
        System.out.println("Creates a new path from the parent abstract pathname and child pathname strings File(Sub path with folder): " + fileTwo);
    }

Operation results:

Creates a new path from the parent abstract pathname and child pathname strings File(Subpath without folder): C:\myFile\example\constructThree.txt
 Creates a new path from the parent abstract pathname and child pathname strings File(Sub path with folder): C:\myFile\example\xxx\constructThree.txt

2.4 File(URI uri)

Create a new File instance by converting the given file: URI to an abstract pathname.

    /**
     * Create a new File instance by converting the given file: URI to an abstract pathname
     */
    @Test
    public void constructFour() throws URISyntaxException {
        //URI 1
        URI uri = new URI("file:/C:/myFile/example/20201124032511.png");
        File file = new File(uri);
        System.out.println("1.according to URI establish File: " + file);
        //URI 2
        File parentFile = new File("C:\\myFile\\example\\");
        URI parentUri = parentFile.toURI();
        File fileUri = new File(parentUri);
        System.out.println("2.according to URI establish File: " + fileUri);
    }

Note: one is the beginning of file:, one is the diagonal bar after file, and the other is the diagonal bar in the path

Operation results:

1.according to URI establish File: C:\myFile\example\20201124032511.png
2.according to URI establish File: C:\myFile\example

3, Common methods

3.1 obtaining path information of files or directories

methodFunction description
String getPath()Returns the pathname string that converts this abstract pathname
File getAbsoluteFile()Returns the absolute pathname of this abstract pathname
String getAbsolutePath()Returns the absolute pathname string of this abstract pathname (navigate from the root directory and return the absolute path)
File getCanonicalFile()Returns the canonical form of this abstract pathname.
String getCanonicalPath()Returns the canonical pathname string for this abstract pathname
String getName()Returns the name of the file or directory represented by this abstract pathname
long length()Returns the length of the file represented by this abstract pathname (only the file size can be returned, not the directory size directly)
boolean exists()Detects whether the file or directory represented by this abstract pathname exists
long lastModified()Returns the time (in milliseconds) when the file represented by this abstract pathname was last modified
String getParent()Returns the pathname string of the parent directory of this abstract pathname; If this pathname does not specify a parent directory, null (returns the parent directory name) is returned
File getParentFile()Returns the abstract pathname of the parent directory of this abstract pathname; If this pathname does not specify a parent directory, null is returned (the File object of the parent directory is returned)
boolean isHidden()Detects whether the file specified by this abstract pathname is a hidden file
boolean isAbsolute()Check whether the File or directory corresponding to the File object is an absolute path
String toString()Returns the pathname string for this abstract pathname
boolean canRead()Detects whether the application can read the file represented by this abstract pathname
boolean canWrite()Detects whether the application can modify the file represented by this abstract pathname

3.2 operation file or directory

methodFunction description
boolean createNewFile()Create a new empty file (if and only if there is no file with the name specified by this abstract pathname)
boolean mkdir()Create the directory specified by this abstract pathname (only one level directory can be created, and the parent directory must exist, otherwise the creation fails.)
boolean mkdirs()Recursively create the directory specified by this abstract pathname (you can create multi-level directories. If the parent directory does not exist, the parent directory will be created together)
boolean delete()Delete the file or directory represented by this abstract pathname (you can delete the file or delete the empty directory)
boolean renameTo(File dest)Rename the file represented by this abstract pathname (you can rename the file or directory)
boolean equals(Object obj)Detects whether this abstract pathname is equal to the given object
boolean isFile()Checks whether the file represented by this abstract pathname is a standard file
boolean isDirectory()Detects whether the file represented by this abstract pathname is a directory
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 representing files in the directory represented by this abstract pathname
static File[] listRoots()Lists the available file system roots

4, Practice

4.1 creating temporary files

    /**
     * Create temporary file
     */
    @Test
    public void createTempFile() throws IOException {
        //Create temporary file
        File tempFile = File.createTempFile("createTempFile", ".pdf");
        System.out.println("Create temporary file:" + tempFile);
        //Create temporary files in the specified directory
        File tempFileWithdirectory = File.createTempFile("createTempFile", ".pdf", new File("C:\\myFile\\example\\"));
        System.out.println("Create temporary files in the specified directory:" + tempFileWithdirectory);
    }

Operation results:

Create temporary file: C:\Users\admin\AppData\Local\Temp\createTempFile4086856944093202796.pdf
 Create temporary files in the specified directory: C:\myFile\example\createTempFile3151981144789119766.pdf

4.2 creating files

    /**
     * create a file
     */
    @Test
    public void createFile() throws IOException {
        //create a file
        File file = new File("C:\\myFile\\example\\createFlie.txt");
        //If the file already exists, it will not be created and a false will be returned
        if (file.createNewFile()) {
            System.out.println("File created successfully");
            System.out.println("The absolute path of the file is:" + file.getAbsolutePath());
        } else {
            System.out.println("Failed to create file");
        }
    }

Operation results:

File created successfully
 The absolute path of the file is: C:\myFile\example\createFlie.txt

4.3 judge whether the document exists

    /**
     * Detect whether the file exists
     */
    @Test
    public void exists() {
        File existentFile = new File("C:\\myFile\\example\\createFlie.txt");
        System.out.println("existentFile Test results:" + existentFile.exists());
        File nonExistentFile = new File("C:\\myFile\\example\\xxx.ftl");
        System.out.println("nonExistentFile Test results:" + nonExistentFile.exists());
    }

Operation results:

existentFile Test results: true
nonExistentFile Test results: false

4.4 get file size

    public long getFileSize(String fileName) {
        File file = new File(fileName);
        //The size of the file is obtained only if the file exists and is a file
        if (!file.exists() || !file.isFile()) {
            System.out.println("file does not exist");
            return -1;
        }
        return file.length();
    }

    /**
     * Get file size
     */
    @Test
    public void getFileSize() {
        long emptyFileSize = getFileSize("C:\\myFile\\example\\createFlie.txt");
        System.out.println("Size of empty file:" + emptyFileSize);
        long csdnFileSize = getFileSize("C:\\myFile\\example\\csdn.txt");
        System.out.println("csdn File size:" + csdnFileSize);
        long nonExistentFileSize = getFileSize("C:\\myFile\\example\\xxx.ftl");
        System.out.println("Size of nonexistent file:" + nonExistentFileSize);
    }

Operation results:

Size of empty file: 0
csdn File size: 53
 file does not exist
 Size of nonexistent file:-1

4.5 last modification time of obtaining or modifying documents

First view the last modification time, then modify the last modification time, and finally obtain the last modification time.

    /**
     * Gets or modifies the last modification time of the file
     */
    @Test
    public void lastModifiedTime() {
        File file = new File("C:\\myFile\\example\\createFlie.txt");
        long lastModifiedBefore = file.lastModified();
        LocalDateTime lastModifiedTimeBefore = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModifiedBefore), ZoneId.systemDefault());
        System.out.println("Last modification time of file before operation:" + lastModifiedTimeBefore);
        boolean modified = file.setLastModified(System.currentTimeMillis());
        System.out.println("Modified results:" + modified);
        long lastModifiedAfter = file.lastModified();
        LocalDateTime lastModifiedTimeAfter = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModifiedAfter), ZoneId.systemDefault());
        System.out.println("Last modification time of file after operation:" + lastModifiedTimeAfter);
    }

Operation results:

Last modification time of documents before operation: 2021-06-24T14:06:11.363
 Modified results: true
 Last modification time of the file after operation: 2021-06-24T14:44:03.878

4.6 file writing

We write a text "alias is testing file writing" to the prepared file WriteFile txt

    /**
     * File write
     */
    @Test
    public void writeFile() throws IOException {
        FileWriter fileWriter = new FileWriter("C:\\myFile\\example\\writeFile.txt");
        BufferedWriter out = new BufferedWriter(fileWriter);
        out.write("Alian Testing file write");
        out.close();
        System.out.println("File written successfully!");
    }

4.7 file content reading

Put the previous step WriteFile Txt to read the contents of the file

    /**
     * read file
     */
    @Test
    public void readFile() throws IOException {
        FileReader fileReader = new FileReader("C:\\myFile\\example\\writeFile.txt");
        BufferedReader in = new BufferedReader(fileReader);
        String str;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }
    }

Operation results:

Alian Testing file write

4.8 setting file read only

Put the file createflight Txt settings file is read-only

    /**
     * Set file read-only
     */
    @Test
    public void readonly() {
        File file = new File("C:\\myFile\\example\\createFlie.txt");
        System.out.println("Result of setting file read-only:" + file.setReadOnly());
        System.out.println("Check whether the file can be read:" + file.canRead());
        System.out.println("Check whether the file can be written:" + file.canWrite());
    }

Operation results:

Result of setting file read-only: true
 Check whether the file can be read: true
 Check whether the file can be written: false

4.9 file renaming

Write the file written above to WriteFile Txt to WriteFile rename txt

    /**
     * File rename
     */
    @Test
    public void rename() {
        File file = new File("C:\\myFile\\example\\writeFile.txt");
        File renameFile = new File("C:\\myFile\\example\\writeFile-rename.txt");
        boolean b = file.renameTo(renameFile);
        System.out.println("Result of file rename:" + b);
    }

Operation results:

Result of file rename: true

4.10 additional data in the document

To the file WriteFile rename Txt added the text "I am the data added!"

    /**
     * Append data to file
     */
    @Test
    public void appendDataToFile() throws IOException {
        FileWriter fileWriter = new FileWriter("C:\\myFile\\example\\writeFile-rename.txt", true);
        BufferedWriter out = new BufferedWriter(fileWriter);
        out.write("\n");
        out.write("I added the data!");
        out.close();
        System.out.println("Append file complete");
        BufferedReader in = new BufferedReader(new FileReader("C:\\myFile\\example\\writeFile-rename.txt"));
        String str;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }
        in.close();
    }

Operation results:

Append file complete
Alian Testing file write
 I added the data!

4.11 document content reproduction

Put the file WriteFile - Rename Txt to another file, copyfiledata txt

    /**
     * File content copy
     */
    @Test
    public void copyFileDataToFile() throws IOException {
        InputStream in = new FileInputStream(new File("C:\\myFile\\example\\writeFile-rename.txt"));
        OutputStream out = new FileOutputStream(new File("C:\\myFile\\example\\copyFileData.txt"));
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("----------------Start getting files copyFileData Content of--------------------");
        BufferedReader reader = new BufferedReader(new FileReader("C:\\myFile\\example\\copyFileData.txt"));
        String str;
        while ((str = reader.readLine()) != null) {
            System.out.println(str);
        }
        reader.close();
    }

Operation results:

----------------Start getting files copyFileData Content of--------------------
Alian Testing file write
 I added the data!

4.12 file deletion

We put the file copyfiledata Txt delete

    /**
     * File deletion
     */
    @Test
    public void fileDelete() {
        File file = new File("C:\\myFile\\example\\copyFileData.txt");
        if (!file.exists() || !file.isFile()) {
            System.out.println("file does not exist");
            return;
        }
        boolean delete = file.delete();
        System.out.println("Result of file deletion:" + delete);
    }

Operation results:

Result of file deletion: true

4.13 judge whether the directory is empty

    /**
     * Determine whether the directory is empty
     */
    @Test
    public void isEmptyDirectory() {
        File file = new File("C:\\myFile\\example");
        if (!file.isDirectory()){
            System.out.println("Not a directory");
            return;
        }
        int list = Objects.requireNonNull(file.list()).length;
        System.out.println("The directory is not empty. The directory size is:"+list);
    }

Operation results:

The directory is not empty. The directory size is: 6

4.14 get the parent directory of the file or directory

Files or directories are OK

    /**
     * Gets the parent directory of the file
     */
    @Test
    public void getParentDirectory() {
        File file = new File("C:\\myFile\\example\\writeFile-rename.txt");
        if (!file.exists()) {
            System.out.println("file does not exist");
            return;
        }
        String parent = file.getParent();
        System.out.println("The parent directory of the file is:" + parent);
    }

Operation results:

The parent directory of the file is: C:\myFile\example

4.15 check whether the file is hidden

    /**
     * Detect whether the file is hidden
     */
    @Test
    public void isHidden() {
        File file = new File("C:\\myFile\\example\\writeFile-rename.txt");
        if (!file.exists() || !file.isFile()) {
            System.out.println("file does not exist");
            return;
        }
        boolean hidden = file.isHidden();
        System.out.println("Detect whether the file is hidden:" + hidden);
    }

Operation results:

Detect whether the file is hidden: false

4.16 create directory

The mkdir method can only create a level-1 directory, and must ensure that the parent directory exists, otherwise the creation fails

    /**
     * Create directory
     */
    @Test
    public void mkdir() {
        File file = new File("C:\\myFile\\example\\test\\");
        if (!file.exists()) {
            boolean mkdir = file.mkdir();
            System.out.println("Create folder results:" + mkdir);
            return;
        }
        System.out.println("Folder already exists");
    }

Operation results:

Create folder results: true

4.17 creating directories recursively

The mkdirs method can create multi-level directories. If the parent directory does not exist, the parent directory will be created together

    /**
     * Create directory recursively
     */
    @Test
    public void mkdirs() {
        File file = new File("C:\\myFile\\example\\test\\alian\\xxx");
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            System.out.println("Recursive folder creation result:" + mkdirs);
            return;
        }
        System.out.println("Folder already exists");
    }

Operation results:

Recursive folder creation result: true

4.18 get current directory

    /**
     * Get current directory
     */
    @Test
    public void currentDir() {
        String currentDir = System.getProperty("user.dir");
        System.out.println("The current working directory is :" + currentDir);
    }

Operation results:

The current working directory is :C:\workspace\study\CSDN

4.19 traverse all files under the directory (specify the directory)

Only the files in the specified directory will be traversed (excluding the files in the subdirectory)

    /**
     * Traverse all files in the directory
     */
    @Test
    public void listFile() {
        File dir = new File("C:\\myFile\\example");
        String[] children = dir.list();
        if (children == null) {
            System.out.println( "The directory does not exist or it is not a directory");
        } else {
            for (String filename : children) {
                System.out.println("C:\\myFile\\example Files in directory:"+filename);
            }
        }
    }

Operation results:

C:\myFile\example Files in directory: createFlie.txt
C:\myFile\example Files in directory: createTempFile285378029982174932.pdf
C:\myFile\example Files in directory: createTempFile3151981144789119766.pdf
C:\myFile\example Files in directory: csdn.txt
C:\myFile\example Files in directory: test
C:\myFile\example Files in directory: writeFile-rename.txt

4.20 traverse all directories under the directory (designated directory)

Only directories under the specified directory will be traversed (excluding directories under subdirectories)

    /**
     * Traverse all directories under the directory
     */
    @Test
    public void listDir() {
        File dir = new File("C:\\myFile\\");
        FileFilter fileFilter = File::isDirectory;
        File[] files = dir.listFiles(fileFilter);
        if (files == null) {
            System.out.println("The directory does not exist or is empty");
            return;
        }
        if (files.length == 0) {
            System.out.println("Number of directories:" + files.length);
            System.out.println("The directory does not exist or it is not a directory");
        } else {
            System.out.println("Number of directories:" + files.length);
            for (File filename : files) {
                System.out.println("C:\\myFile Directory under Directory:" + filename.toString());
            }
        }
    }

Operation results:

Number of directories: 6
C:\myFile Directory under Directory: C:\myFile\companyImage
C:\myFile Directory under Directory: C:\myFile\CSDN
C:\myFile Directory under Directory: C:\myFile\document
C:\myFile Directory under Directory: C:\myFile\example
C:\myFile Directory under Directory: C:\myFile\invoice
C:\myFile Directory under Directory: C:\myFile\PDF

4.21 traversing directories (including subdirectories)

Contains the directories and files in the current directory and subdirectories (recursion)

    public void listAllDirsAndFiles(File directory) {
        System.out.println(directory);
        if (directory.isDirectory()) {
            String[] children = directory.list();
            if (children==null){
                return;
            }
            for (String child : children) {
                listAllDirsAndFiles(new File(directory, child));
            }
        }
    }

    /**
     * Traverse directory
     */
    @Test
    public void listAllDir() {
        File directory = new File("C:\\myFile\\example");
        listAllDirsAndFiles(directory);
    }

Operation results:

C:\myFile\example
C:\myFile\example\copyFileData.txt
C:\myFile\example\createFlie.txt
C:\myFile\example\createTempFile285378029982174932.pdf
C:\myFile\example\createTempFile3151981144789119766.pdf
C:\myFile\example\createTempFile3607700977130726322.pdf
C:\myFile\example\csdn.txt
C:\myFile\example\test
C:\myFile\example\test\alian
C:\myFile\example\test\alian\xxx
C:\myFile\example\writeFile-rename.txt
C:\myFile\example\writeFile.txt

4.22 delete directory

If you want to delete the package subdirectory in the directory, you will continue to traverse the subdirectory,... Until it is a file or an empty directory

    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children != null) {
                for (String child : children) {
                    boolean success = deleteDir(new File(dir, child));
                    if (!success) {
                        return false;
                    }
                }
            }
        }
        if (!dir.delete()) {
            System.out.println("Catalogue[" + dir + "]Deletion failed!");
            return false;
        }
        System.out.println("Catalogue[" + dir + "]Deleted!");
        return true;

    }

    /**
     * Traverse directory
     */
    @Test
    public void deleteDir() {
        deleteDir(new File("C:\\myFile\\example\\test"));
    }

Operation results:

Catalogue[ C:\myFile\example\test\alian\xxx]Deleted!
Catalogue[ C:\myFile\example\test\alian]Deleted!
Catalogue[ C:\myFile\example\test]Has been deleted!

epilogue

   the above is what we want to talk about today. This article only briefly introduces the operation of files, file directories and their files and file directories, as well as the common operation methods. Later, I will continue to write about file flow.

Keywords: Java Back-end

Added by nitestryker on Mon, 24 Jan 2022 18:29:44 +0200