Introduction to the

Directory and file silly silly division is not clear, directory and the essence of the file is what? How to manipulate and traverse directories in Java. In this article, brother F will tell you one by one.

Files and directories in Linux

Brother F, I have a question recently. It seems that there are only files without directories in Java code. Is it possible that the god who invented Java accidentally lost his mind?

Brother F: My sister’s courage is admirable. The courage to question authority is the most important step from a laborer to an expert. Think of F elder brother I, since childhood no one mention point, the teacher speak what I believe what, the expert say what I listen to what: the stock market must go up ten thousand point, the house is to give a person to live is not to give a person to fry, crude oil treasure is of course small white finance essential product…. And then, there is no then.

More highlights:

  • Blockchain from getting started to Giving up series tutorials – with ongoing updates covering cryptography, Hyperledger, Ethereum,Libra, Bitcoin and more
  • Spring Boot 2.X Series tutorials: Learn Spring Boot from Scratch in seven days – continuous updates
  • Spring 5.X Series tutorials: Everything you can think of in Spring5 – constantly updated
  • Java Programmer from Handyman to Expert to God (2020 edition) – Ongoing updates with detailed articles and tutorials

For more, visit www.flydean.com

Although there is no such thing as a directory in Java as a File File, File can actually represent a directory:

public boolean isDirectory(a)
Copy the code

File has an isDirectory method to determine whether the File is a directory.

I don’t know the difference between File and directory. Do you think of anything?

Brother F, I remember you said last time that all resources under Linux can be regarded as files. Are the essence of files and directories the same under Linux?

Yes, under Linux files are first-class citizens, and all resources are classified as files.

The underlying structure of sectors, logical blocks, pages, etc., will not be covered. Let’s start by thinking about what a file should contain. In addition to the data of the file itself, there are a lot of metadata things, such as file permissions, owner, group, creation time and so on.

In Linux, these two parts are stored separately. Blocks that hold the data itself are called blocks, and inodes that hold metadata are called inodes.

Inodes store block addresses. You can use inodes to find the block addresses of file data stores for file access. Consider that large files can occupy many blocks, so an inode can store the addresses of multiple blocks, and one inode is generally sufficient for a file.

In order to display hierarchical relationship and facilitate file management, the data files of a directory store files in the directory and their inode addresses, thus forming a chain relationship of ring by ring and ring by ring.

The figure above shows a ring layout that looks for files under it by directory.

I think the reason why Java directories don’t list a single class is because they refer to the underlying file layout of Linux.

Basic operations for directories

Because directories and files are common to the File class in Java, the basic operation directory of File will be all of it.

Basically, there are three methods to pay more attention to directories than files:

public boolean isDirectory(a)
public File[] listFiles(a) 
public boolean mkdir(a) 
Copy the code

Why three? Because there are several approaches that are closer to them, I will not list them here.

IsDirectory Checks whether the file is a directory. ListFiles lists all files under this directory. Mkdir Creates a file directory.

Brother F, we used to take a long time to traverse the directory. After you explained the data structure of the directory, WE felt that listFiles is not a time-consuming operation. All the data is ready, and we can read it directly.

Yes, do not look at the surface of the problem, to see the hidden essence of the surface. You see, I am usually not prominent, in fact, I am a real pillar of the company, a model of excellent employees.

Junior sister: Brother F, I haven’t seen what you are praised for? Ll: Well, the boss is afraid that if he recognizes you, it will make others jealous and ruin your image.

Advanced operations for directories

Good little sister, you understand the line, the following brother F to tell you about the directory of advanced operations, such as how we copy a directory ah?

Little sister, copy directory is simple, brother F, last time you taught me:

cp -rf
Copy the code

Wouldn’t that be enough for a command? Is there something hidden in there?

Cough cough cough, secret is not, small teacher sister, I remember you last said to Java from the end of the day, today the teacher brother to give you a copy of the file directory in Java method.

The Files utility class already provides an excellent way to copy Files:

public static Path copy(Path source, Path target, CopyOption... options)
Copy the code

Using this method, we can make a copy of the file.

If you want to copy a directory, you simply iterate over the files in the directory and call the copy method.

Wait, brother F, what should I do if there is a directory under the directory and another directory under the directory?

That’s the trick. Watch me solve it recursively:

public void useCopyFolder(a) throws IOException {
        File sourceFolder = new File("src/main/resources/flydean-source");
        File destinationFolder = new File("src/main/resources/flydean-dest");
        copyFolder(sourceFolder, destinationFolder);
    }

    private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
    {
        // Create dir recursively if it is dir, copy it directly if it is file
        if (sourceFolder.isDirectory())
        {
            // Check whether the target dir exists
            if(! destinationFolder.exists()) { destinationFolder.mkdir(); log.info("Target dir already created: {}",destinationFolder);
            }
            for (String file : sourceFolder.list())
            {
                File srcFile = new File(sourceFolder, file);
                File destFile = newFile(destinationFolder, file); copyFolder(srcFile, destFile); }}else
        {
            // Use files. copy to copy specific Files
            Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
            log.info("Copy object file: {}",destinationFolder); }}Copy the code

The basic idea is I traverse directories whenever I see them, and I copy files whenever I see them.

Directory of low back pain operation

Brother F, if I want to delete files in a directory, or we want to count how many files there are under the directory, what should I do?

The Files utility class has a method called Walk that returns a Stream object. We can use the Stream API to process the file.

Delete file:

public void useFileWalkToDelete(a) throws IOException {
        Path dir = Paths.get("src/main/resources/flydean");
        Files.walk(dir)
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
    }
Copy the code

Statistical Documents:

 public void useFileWalkToSumSize(a) throws IOException {

        Path folder = Paths.get("src/test/resources");
        long size = Files.walk(folder)
                .filter(p -> p.toFile().isFile())
                .mapToLong(p -> p.toFile().length())
                .sum();
        log.info("dir size is: {}",size);
    }
Copy the code

conclusion

This article covered some very common and useful operations for directories.

Examples of this article github.com/ddean2009/l…

Author: Flydean program stuff

Link to this article: www.flydean.com/java-io-dir…

Source: Flydean’s blog

Welcome to pay attention to my public number: procedures those things, more wonderful waiting for you!