Java File class, do you know what api methods are there?

Keywords: Java Maven SHA1 network

If you think this article is helpful to you, welcome old fellow to praise you. Your support is the biggest driving force for my creation.

Article catalog

1 foreword

The File class in Java is still used more in actual development. For example, when reading resources, when uploading and downloading files and other scenarios, here's a summary. In the future, it's very convenient to query the api.

2 File class

Java file classes represent file names and directory pathnames in an abstract way. This class is mainly used for creating files and directories, finding files and deleting files.

The File object represents the files and directories that actually exist on the disk.

3 create a File object

You can create a File object by using one of the following four construction methods:

Create a new File instance with the given parent abstract pathname and child pathname string
File(File parent, String child)

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

Create a new File instance based on the parent pathname string and the child pathname string
File(String parent, String child)

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

4 common methods in file object

After creating the File object successfully, you can use the methods in the following table to manipulate the File:

No Method name Method description
1 public String getName() Returns the name of the file or directory represented by this abstract pathname
2 public String getParent() Returns the pathname string of the parent pathname of this abstract pathname, or null if the pathname does not specify a parent directory
3 public File getParentFile() Returns the abstract pathname of the parent pathname of this abstract pathname, or null if no parent directory is specified for this pathname
4 public String getPath() Convert this abstract pathname to a pathname string
5 public boolean isAbsolute() Determine whether the abstract path name is an absolute path name
6 public String getAbsolutePath() Returns the absolute pathname string of the abstract pathname
7 public boolean canRead() Determine whether the application can read the file represented by this abstract pathname
8 public boolean canWrite() Determine whether the application can modify the file represented by this abstract pathname
9 public boolean exists() Determine whether the file or directory represented by this abstract pathname exists
10 public boolean isDirectory() Determine whether the file represented by this abstract pathname is a directory
11 public boolean isFile() Determine whether the file represented by this abstract pathname is a standard file
12 public long lastModified() Returns the time when the file represented by this abstract pathname was last modified
13 public long length() Returns the length of the file represented by this abstract pathname
14 public boolean createNewFile() throws IOException If and only if there is no file with the name specified by this abstract pathname, a new empty file specified by this abstract pathname is created atomically
15 public boolean delete() Delete the file or directory represented by this abstract pathname
16 public void deleteOnExit() Request to delete the file or directory represented by this abstract pathname when the virtual machine terminates
17 public String[] list() Returns a string array of the names of files and directories in the directory represented by this abstract pathname
18 public String[] list(FilenameFilter filter) Returns an array of strings consisting of the names of the files and directories contained in the directory represented by an abstract pathname that satisfies the specified filter
19 public File[] listFiles() Returns an array of abstract pathnames representing files in the directory represented by the abstract pathname
20 public File[] listFiles(FileFilter filter) Returns an array of abstract pathnames representing files and directories in the directory represented by this abstract pathname, which satisfy the specific filter
21 public boolean mkdir() Create the directory specified by this abstract pathname
22 public boolean mkdirs() Create the directory specified by this abstract pathname, including creating a required but nonexistent parent directory
23 public boolean renameTo(File dest) Rename the file represented by this abstract pathname
24 public boolean setLastModified(long time) Sets the last modification time of the file or directory specified by this abstract pathname
25 public boolean setReadOnly() Marks the file or directory specified by this abstract pathname so that it can only be read
26 public static File createTempFile(String prefix, String suffix, File directory) throws IOException Creates a new empty file in the specified directory and generates its name with the given prefix and suffix string
27 public static File createTempFile(String prefix, String suffix) throws IOException Create an empty file in the default temporary file directory and generate its name with the given prefix and suffix
28 public int compareTo(File pathname) Compare two abstract pathnames in alphabetical order
29 public int compareTo(Object o) Alphabetically compare Abstract pathnames with given objects
30 public boolean equals(Object obj) Determine whether the abstract pathname is equal to the given object
31 public String toString() Returns the pathname string for this abstract pathname

5 File usage instance

5.1 basic use of file

[code example]

/**
 * @author smilehappiness
 * File Object, the use of basic api
 * @version 1.0
 * @ClassName FileUse
 * @Date 2020/6/6 15:40
 */
public class FileUse {

    public static void main(String args[]) {
        //Directory name of the test
        String dirName = "d:\\test-case";
        File file = new File(dirName);
        //Determine whether the abstract pathname is a directory type
        if (file.isDirectory()) {
            System.out.println("Directory of " + dirName);

            //Returns a string array of the names of files and directories in the directory represented by this abstract pathname
            String stringArrays[] = file.list();
            for (int i = 0; i < stringArrays.length; i++) {
                File f = new File(dirName + "/" + stringArrays[i]);
                if (f.isDirectory()) {
                    System.out.println(stringArrays[i] + " is a directory");
                } else {
                    System.out.println(stringArrays[i] + " is a file");
                }
            }

            System.out.println("------------------Gorgeous dividing line------------------");
            //Returns an array of abstract pathnames representing files in the directory represented by the abstract pathname
            File fileArrays[] = file.listFiles();
            for (File fileArray : fileArrays) {
                File f = new File(dirName + "/" + fileArray);
                if (f.isDirectory()) {
                    System.out.println(fileArray + " is a directory");
                } else {
                    System.out.println(fileArray + " is a file");
                }
            }

            //Determine whether this abstract path name is a standard file type
        } else if (file.isFile()) {
            System.out.println(dirName + " is not a directory");
        }
    }

}

Execution result:

Directory of d:\test-case
hello is a directory
log.txt is a file
Person.dat is a file
test.txt is a file
test.txt.bak is a file
------------------Gorgeous dividing line------------------
d:\test-case\hello is a file
d:\test-case\log.txt is a file
d:\test-case\Person.dat is a file
d:\test-case\test.txt is a file
d:\test-case\test.txt.bak is a file

5.2 obtaining failed dependencies in maven warehouse

At present, maven is widely used in project construction, but when maven is used, some jar s may fail to download due to the unstable network or the need to climb over the wall. Only re download can make the project start normally. However, the failure of download depends on the failure of download. If you do not delete it and the download is not successful, the project will start with an error.

How to quickly find which dependency reported an error? Find the failed dependencies, delete them and download them again. Most of them succeed without nagging. See the following solution example:

/**
 * @author smilehappiness
 * 
 * By reading the path of the specified file name in the specified directory and subdirectory, obtain the required resources, and the return result is List
 * @version 1.0
 * @ClassName MavenFailDependency
 * @Date 2020/6/6 14:13
 */
public class MavenFailDependency {

    /**
     * <p>
     * Obtain the resource file under the directory by specifying the path and matching content suffix
     * <p/>
     *
     * @param path   File path
     * @param suffix Suffix name, file matching specific suffix content
     * @return java.util.List<java.lang.String>
     * @Date 2020/6/6 14:20
     */
    public static List<String> getFilesList(String path, String suffix) {
        File file = new File(path);
        return MavenFailDependency.listFile(new ArrayList<>(), file, suffix);
    }

    /**
     * <p>
     * Gets the resource file of the specified suffix content in the directory
     * For example, the failure depends on aether-ed239b5e-5ab7-49c1-8f71-df76605fb76e-spring-beans-5.0.5 RELEASE.jar.sha1 -in-progress
     * At the end of in progress is the dependency of download failure. The common suffix of download failure is. SHA1 in progress /. Jar in progress /. POM in progress
     * <p/>
     *
     * @param fileNameList
     * @param file
     * @param suffix
     * @return java.util.List<java.lang.String>
     * @Date 2020/6/6 14:30
     */
    private static List<String> listFile(List<String> fileNameList, File file, String suffix) {
        if (StringUtils.isBlank(suffix)) {
            return Collections.emptyList();
        }

        // If it is a directory, recursively traverse subdirectories( file.isFile(), file.isDirectory())
        if (file.isDirectory()) {
            // Get all the sub files in the source directory (there are directories or files in the sub files)
            File[] fileList = file.listFiles();

            for (File subFile : fileList) {
                //Recursive call
                listFile(fileNameList, subFile, suffix);
            }
        } else {
            // Get the absolute path of the file
            String filePath = file.getAbsolutePath();
            // Index of the last. (i.e. the
            int begIndex = filePath.lastIndexOf(".");
            // Here you can filter the files with the specified suffix
            if (begIndex != -1) {
                //Get to the last. End
                String suffixValue = filePath.substring(begIndex + 1);
                // SHA1 in progress contains in progress
                // Here, because the specified suffix is not the same as the suffix and name of the truncated. So add one|| tempSuffix.contains(suffix) condition
                if (suffixValue.equals(suffix) || suffixValue.contains(suffix)) {
                    fileNameList.add(filePath);
                }
            }
        }

        return fileNameList;
    }

}

Test case:

/**
 * <p>
 * Quick access, in maven warehouse, failed dependency, find failed dependency, delete, download again, function test
 * <p/>
 *
 * @author smilehappiness
 * @Date 2020/6/6 14:55
 */
public class MavenFailDependencyTest {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Test
    public void testGetMavenFailDependency() {
        //Local maven warehouse, depending on the download and saved address
        String localMavenRepositoryDir = "D:\\workplace\\worktool\\maven";
        List<String> list = MavenFailDependency.getFilesList(localMavenRepositoryDir, "in-progress");
        logger.info("Number of dependency download failures:{}", list.size());

        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                logger.info("Dependent download failed directory{}: {}", i, list.get(i));
            }
        }
    }

}

5.3 copy of documents and directories

5.3.1 document copying tools

Summarize a copy tool category for the old fellow:

/**
 * <p>
 * File copying tool class
 * <p/>
 *
 * @author smilehappiness
 * @Date 2020/6/6 11:56
 */
public class FileCopyUtil {

    private FileCopyUtil() {

    }

    /**
     * <p>
     * Copy file function
     * <p/>
     *
     * @param srcFile Source file (path)
     * @param desPath Target path
     * @return void
     * @Date 2020/6/6 11:57
     */
    public static void copyFile(String srcFile, String desPath) {
        // String -> File
        copyFile(new File(srcFile), desPath);
    }

    /**
     * <p>
     * Copy file function
     * <p/>
     *
     * @param srcFile Source file (file type)
     * @param desPath Target path
     * @return void
     * @Date 2020/6/6 12:01
     */
    public static void copyFile(File srcFile, String desPath) {
        // 1. Extract the source file name
        String fileName = srcFile.getName();

        // 2. Judge whether the target path exists
        File dPath = new File(desPath);
        if (!dPath.exists()) {
            //The destination path of the copy. If the directory does not exist, create the directory
            // boolean mkdir() creates the directory specified by the abstract pathname, and creates the directory specified by the abstract pathname, including all required but nonexistent parent directories.
            System.out.println("Create target path successfully:" + dPath.mkdirs());
        }

        // 3. Set the target file name
        //static String separator() is the system specific default name separator, which is represented as a string for convenience.
        String desFileName = desPath + File.separator + fileName;

        // Declare low level flow
        FileInputStream fileInputStream;
        FileOutputStream fileOutputStream;

        // Declare advanced flow
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;

        try {
            // When initializing, first initialize the low-level stream (FileInputStream is the file byte input stream, FileOutputStream is the file byte output stream)
            fileInputStream = new FileInputStream(srcFile);
            fileOutputStream = new FileOutputStream(desFileName);

            // Then initialize the advanced stream and use the buffer stream to improve io performance
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            int i = 0;
            byte[] b = new byte[1024 * 1024];
            while ((i = bufferedInputStream.read(b)) != -1) {
                bufferedOutputStream.write(b, 0, i);
            }

            System.out.println(srcFile + " Copy files to target directory[" + desPath + "]Done!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // When the advanced stream bout is closed, the JVM will automatically refresh the buffer, that is, it will automatically call the flush method to refresh the buffer before closing the stream
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * <p>
     * Copy directory function
     * <p/>
     *
     * @param srcPath Source directory (path)
     * @param desPath Target directory
     * @return void
     * @Date 2020/6/6 13:13
     */
    public static void copyDir(String srcPath, String desPath) {
        copyDir(new File(srcPath), desPath);
    }

    /**
     * <p>
     * Copy directory function
     * <p/>
     *
     * @param srcPath Source directory (file type)
     * @param desPath Target directory
     * @return void
     * @Date 2020/6/6 13:20
     */
    public static void copyDir(File srcPath, String desPath) {
        // Determine whether srcPath is a file or a directory
        if (srcPath.isFile()) {
            // Recursive call, if it is a file, continue to call until it is a directory
            copyFile(srcPath, desPath);
        } else {
            // Get all the sub files in the source directory
            File[] files = srcPath.listFiles();

            // Get the name of the directory to be copied from the source directory, for example: get the name of the directory "test case" from the "D: \ \ test case" source directory
            String srcPathName = srcPath.getName();

            // Create the name of the directory to be copied in the target path, for example, create the src directory in d: \ \
            String descPathName = desPath + File.separator;
            // Create a new File instance by converting the given pathname string to an abstract pathname
            File filePath = new File(descPathName);

            // Create the directory specified by this abstract pathname, including all required but nonexistent parent directories
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            // Traversal array, a copy of a directory
            for (File file : files) {
                // Recursive call
                copyDir(file, descPathName);
            }
        }
    }

}

5.3.2 function of copying documents

/**
 * <p>
 * Copy file function - Test
 * <p/>
 *
 * @param
 * @return void
 * @Date 2020/6/6 13:33
 */
@Test
public void testCopyFile() {
    String srcFile = "D:\\test-case\\log.txt";
    FileCopyUtil.copyFile(srcFile, "d:\\test-case\\src");
}

5.3.3 function of copying file directory

 /**
     * <p>
     * Copy directory function
     * <p/>
     *
     * @param
     * @return void
     * @Date 2020/6/6 13:43
     */
    @Test
    public void testCopyDir() {
        String srcFile = "D:\\test-case";
        FileCopyUtil.copyDir(srcFile, "c:\\test-case\\test");
    }

6 Summary

This paper mainly introduces the use of file object basic api in Java. The author uses File api method commonly used to write some cases, to the old fellow iron to deepen the impression of api method. File objects are relatively used, and hope that the old fellow iron companies will have more connections and mastery.

reference material: https://www.runoob.com/java/java-file.html

Blogging is to remember what you forget easily. It's also a summary of your work. I hope you can do your best and make progress together!

If there is any problem, please comment and discuss together. If there is any problem with the code, please correct it!

Add a pair of wings to your dream, let it fly freely in the sky!

Posted by Marino on Sat, 06 Jun 2020 02:08:45 -0700