Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This paper introduces the File class File in Java IO and how to use it.

1 Overview of File objects

public class File
extends Object
implements Serializable, Comparable<File>
Copy the code

I/O streams cannot operate file properties, search, add or delete, but only internal data in files.

File properties: Descriptive information about a file that is not included in the actual content of the file and can be used to help find and organize the file. For example: whether the file is readable and writable; A. TXT is a file or directory; A. whether the file is hidden; File modification date and so on are file attributes

File is an abstract representation of a File or folder (directory). This class is mainly used for File property operations, directory creation, File search, and File deletion. File objects represent files and directories that actually exist on disk.

File is usually used in combination with IO streams, so the File object is called an auxiliary object of IO streams, and the File class is an auxiliary class of IO streams.

2 Static Fields

Static fields can be called directly by the class name.

public static final char separatorChar

A name separator associated with the system. Represents the char type. On UNIX systems, the value of this field is “/”; on Windows systems, it is “\”.

public static final String separator

System – related name delimiter to facilitate its representation as a string.

public static final String pathSeparatorChar

The path separator associated with the system. Represents the char type. On UNIX systems, this field is’ : ‘; on Microsoft Windows systems, it is’; ‘.

public static final String pathSeparator

System – related path separator to facilitate representation as a string.

3 the constructor

public File(File parent,String child)

Creates a new File instance based on the parent abstract pathname and child pathname strings. Parent + Child: File file3 = new File(“e:\demo”); File file4 = new File(file3, “a.txt”);

public File(String pathname)

Creates a new File instance by converting the given pathname string to an abstract pathname. If the path is not correct, a file/directory will not be created for that path!

File File = new File(” e:\demo\ a.tep “);

public File(String parent,String child)

Creates a new File instance based on the parent pathname string and child pathname string. This method is used when a parent directory has multiple subdirectories.

File file2 = new File(“E:\demo”, “a.txt”);

Note: If a relative path is used, it is relative to the current project!

4 API methods

4.1 Related to creation

All return Boolean values.

public boolean createNewFile()

Can only be used to create files. Returns true if the specified file did not exist and was successfully created; If the specified file already exists, it will not be created and returns false; If the specified directory does not exist, an exception is thrown. You can create files without name extensions.

public boolean mkdir()

Can only be used to create a directory, return true if and only if a directory has been created. Otherwise, return false, the multilevel directory will not be created.

public boolean mkdirs()

Has the properties and functionality of the mkidr method, and can also create multi-level directories.

Note:

  1. If either method creates a file or directory in a certain directory, the other two methods cannot create a file or directory with the same name (including the suffix) in the same directory.
  2. If no path is specified, relative to the project path!

4.2 Related to deletion

Returns a Boolean value

public boolean delete()

Deletes the file or directory represented by this abstract pathname. Return true if and only if a file or directory is successfully deleted; Otherwise return false.

If the pathname represents a directory, the directory must be empty (there can be no directories or files in the directory).

If the file/directory is occupied by other programs, it cannot be deleted.

Files or directories that are deleted using Java commands can be directly deleted without going through the recycle bin.

deleteOnExit();

When the virtual machine terminates, the file or directory represented by this abstract pathname is requested to be deleted.

4.3 Related to judgment

Returns a Boolean value

public boolean exists()

Tests whether the file or directory represented by this abstract pathname exists. Often used with createNewFile (to create a file) and mkdir (to create a directory).

Returns true if and only if the file or directory represented by this abstract pathname exists; Otherwise return false

public boolean isFile()

Tests whether the file represented by this abstract pathname exists and is a standard file. A file is a standard file if it is not a directory and meets other system-related criteria. All non-directory files created by Java applications must be standard files.

Returns true if and only if the file represented by this abstract pathname exists and is a standard file; Otherwise return false

public boolean isDirectory()

Tests whether the file represented by this abstract pathname is a directory.

Returns true if and only if the file represented by this abstract pathname exists and is a directory; Otherwise return false

public boolean isAbsolute()

Tests whether this abstract pathname is an absolute pathname. On UNIX systems, a pathname is an absolute pathname if it is prefixed with a “/”. On Microsoft Windows systems, a pathname is an absolute pathname if it is prefixed with a drive letter followed by “\”, or if it is “\\”.

Returns true if the abstract pathname is an absolute pathname; Otherwise return false

An absolute path: C: / Users/Mrzhang/javaEE/javaSE – 10 / javaSE – 32 / b.t xt

Relative path: Relative to a location

A file’s path a is c:/a/a.txt and path B is C :/b/b.txt

Ask to find b.tuct at the location of a.tuct:

  1. Use the absolute path to find b.txt c:/b/b.txt;
  2. Relative path:.. B.t/xt or.. /.. /b/b.txt;

public boolean isHidden()

Check whether the file specified by the path name is hidden.

public boolean canRead();

Determine whether it is readable

public boolean canWrite();

Determine if it is writable

public boolean canExecute();

Determine whether it can be executed

4.4 Related to access to information

public String getName()

Gets the string form name of this abstract pathname.

This name is the last name in the sequence of pathname names. If the pathname name sequence is empty, an empty string is returned. It does not determine whether the file/directory represented by the path exists.

public String getPath()

Gets the string form of this abstract pathname

If the abstract path is an absolute path: getPath(); Acquisition is the absolute path.

If the abstract path specifies a relative path, getPath() gets the relative path.

public String getParent()

Gets the string form of the parent directory of this abstract pathname

If an absolute path is specified: Get the parent path, the directory above the file

If the specified file is a relative path that has no parent directory, null is returned

If the specified relative path has a parent directory, the parent directory is returned.

public String getAbsolutePath()

Gets the absolute pathname string for this abstract pathname.

Whether it’s an absolute path or an abstract path, you get an absolute path.

public long length()

Returns the length (in bytes) of the file represented by this abstract pathname. If the pathname represents a directory, the return value is indeterminate.

public long lastModified()

Gets the time when the file represented by this abstract pathname was last modified.

Returns the value of long representing the time when the file was last modified, in milliseconds from the point in time (January 1, 1970, 00:00:00 GMT); If the file does not exist, or an I/O error occurs, 0L is returned

4.5 File Filtering

public static File[] listRoots()

List the available file system roots (list drive letters) into the array. Returns an array of type File.

public String[] list()

The ability to encapsulate the names of all direct files and directories in the abstract directory into the returned array. The value is an array of String.

public File[] listFiles()

The ability to encapsulate all direct files and directories in an abstract directory into a returned array. Returns an array of abstract pathnames.

public File[] listFiles(FileFilter filter)

Returns an array of abstract pathnames representing files and directories in the directory represented by this abstract pathname that satisfy the specified filter.

Filter: filters file and directory names. FileFilter is an interface type, KDJ1.2, that should be passed an implementation class for the interface when used. Anonymous inner classes can be used.

public String[] list(FilenameFilter filter)

Returns a String array of file/directory names that satisfy the filter.

public File[] listFiles(FilenameFilter filter)

Returns an array of strings specifying the files and directories in the directory represented by this abstract pathname that satisfy the specified filter.

Boolean accept(File dir,String name), dir: specifies the directory where the File is found. Name: indicates the file name.

1.1.4.6. Other methods

Return Boolean type

public boolean renameTo(File dest)

Renames the file represented by this abstract pathname. If the paths are the same, change the name. If the paths are different, cut and paste

setReadOnly()

Set the file to read-only

setWritable(boolean writable)

Sets whether to be writable

5 cases

5.1 Output File Name

Check if there is a file with the suffix.jpg in a disk directory. If there is, print the file name.

Method 1: Get all the resources first, then judge

@Test
public void test1(a) {
    File file = new File("e:\\");
    File[] files = file.listFiles();
    for (File file1 : files) {
        if (file1.isFile()) {
            if (file1.getName().endsWith(".jpg")) { System.out.println(file1.getName()); }}}}Copy the code

Method 2: Make a judgment while obtaining the resource

@Test
public void test2(a) {
    / / use FileFilter
    File file = new File("e:\\");
    File[] files = file.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file1) {
            return file1.isFile() && file1.getName().endsWith(".jpg"); }});for (File file1 : files) {
        System.out.println(file1.getName());
    }
    / / use FilenameFilter
    /*File file = new File("e:\\"); File[] files = file.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { File file1 = new File(dir, name); return file1.isFile() && file1.getName().endsWith(".jpg"); }}); for (File file1 : files) { System.out.println(file1.getName()); } * /
}
Copy the code

5.2 Deleting a Directory

Window The mechanism for deleting a directory is as follows: Deletes a directory from the inside out

  1. Recurse to the bottom of the directory.

  2. Delete existing files from the directory first.

  3. Then delete the empty directory.

static void delete(String path) {
    File file = new File(path);
    if (file.exists()) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isFile()) {
                file1.delete();
            } else{ delete(file1.getPath()); } } file.delete(); }}Copy the code

5.3 Listing files

List all the file names that meet the rules under a folder into a directory in another TXT file.

/** * lists the files **@paramSource Directory to traverse *@paramPlace File name Path of the output file */
public static void makeList(String source, String place) {
    ArrayList<String> al = new ArrayList<>();
    File file = new File(source);
    File[] files = file.listFiles();
    assertfiles ! =null;
    for (File file1 : files) {
        if (file1.isFile()) {
            al.add(file1.getAbsolutePath());
        } else {
            // Recursively iterate through all filesmakeList(file1.getAbsolutePath(), place); }}if (al.isEmpty()) {
        return;
    }
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(place, true))) {
        / / written
        for(String s : al) { bw.write(s); bw.newLine(); bw.flush(); System.out.println(s); }}catch(IOException e) { e.printStackTrace(); }}Copy the code

If you need to communicate, or the article is wrong, please leave a message directly. In addition, I hope to like, collect, pay attention to, I will continue to update a variety of Java learning blog!