Junior sister learning java IO: directory or file

brief introduction

What is the essence of directory and file? How to manipulate and traverse directories in Java. Senior brother f will tell you one by one.

Files and directories in Linux

Younger martial sister: Senior brother F, I have a doubt recently. It seems that there are only files and no directories in Java code. Did the great God who invented Java accidentally go away?

Senior brother F: I'm so brave, younger martial sister. It's the most important step from a small worker to an expert to dare to question authority. Think about elder martial brother F. since I was a child, no one has mentioned anything. I believe what the teacher says, and I listen to what the experts say: the stock market must be 10000 points. The house is for people to live in, not for people to fry. Of course, crude oil treasure is a necessary product for Xiaobai's financial management Then, there is no then.

More highlights:

Although there is no concept of directory in Java, only file file can represent Directory:

public boolean isDirectory()

There is an isdirectory method in file to determine whether the file is a directory.

I can't tell the file from the directory. Younger martial sister, do you think of anything?

Younger martial sister: elder martial brother F, I remember you said last time that all resources under Linux can be regarded as files. Is the essence of files and directories under linux the same?

Yes, under Linux, files are first-class citizens, and all resources are distinguished in the form of files.

We won't talk about the underlying structures such as sectors, logical blocks and pages. Let's first consider what a file should contain. In addition to the data of the file itself, there are many metadata, such as file permission, owner, group, creation time and so on.

In Linux system, these two parts are stored separately. The storage of data itself is called a block, and the storage of metadata is called an inode.

Inode stores the address of the block. You can find the block address of the actual data storage of the file through inode, so as to access the file. Considering that large files may occupy many blocks, the addresses of multiple blocks can be stored in an inode, and one inode is usually enough for a file.

In order to display the hierarchical relationship and facilitate the management of files, the data files of the directory store the inode addresses of the files and files under the directory, thus forming a chain relationship of one ring over one ring and one ring over one ring.

The figure above shows a ring in ring layout in which files can be found through a directory.

I think the reason why a class is not listed separately in the Java directory may be that it refers to the underlying file layout of Linux.

Basic operation of directory

Because in Java, directories and files share the file class, the basic operation directory of file will be changed.

Basically, pay more attention to the following three methods than directories and files:

public boolean isDirectory()
public File[] listFiles() 
public boolean mkdir() 

Why three categories? Because there are several methods close to them, I won't list them one by one here.

Isdirectory determines whether the file is a directory. Listfiles lists all files under the directory. MKDIR creates a file directory.

Younger martial sister: elder martial brother F, it took us a long time to traverse the directory. Once you explain the data structure of the directory, you feel that listfiles is not a time-consuming operation. All the data is ready and can be read directly.

Yes, look at the problem, don't look at the surface, but see the essential connotation hidden on the surface. You see, elder martial brother, I usually don't show my talents. In fact, I am the real mainstay and can be called an excellent employee model of the company.

Younger martial sister: elder martial brother F, I don't usually see the commendation from the top? Oh, I see. The boss must be afraid that praising you will cause other people's jealousy and collapse your good senior brother's image. It seems that the boss really understands you.

Advanced operation of directory

OK, younger martial sister, just understand. Next, senior brother f will tell you about the advanced operation of the directory, such as how we copy a directory?

Younger martial sister, senior brother F, who copies the directory simply, you taught me last time:

cp -rf

Isn't the matter of an order solved? Is there a secret in it?

Cough, cough, there's no secret. Younger martial sister, I remember you said you wanted to be consistent with Java last time. Today, senior brother introduced you a method to copy files and directories in Java.

In fact, the files tool class has provided us with an excellent method to copy files:

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

Using this method, we can copy the file.

If you want to copy the directory, traverse the files in the directory and call the copy method repeatedly.

Younger martial sister: wait a minute, senior brother F, what should I do if there is a directory under the directory and a set of directories under the directory?

This is a trap. Let me solve it recursively:

public void useCopyFolder() 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
    {
        //如果是dir则递归遍历创建dir,如果是文件则直接拷贝
        if (sourceFolder.isDirectory())
        {
            //查看目标dir是否存在
            if (!destinationFolder.exists())
            {
                destinationFolder.mkdir();
                log.info("目标dir已经创建: {}",destinationFolder);
            }
            for (String file : sourceFolder.list())
            {
                File srcFile = new File(sourceFolder,file);
                File destFile = new File(destinationFolder,file);
                copyFolder(srcFile,destFile);
            }
        }
        else
        {
            //使用Files.copy来拷贝具体的文件
            Files.copy(sourceFolder.toPath(),destinationFolder.toPath(),StandardCopyOption.REPLACE_EXISTING);
            log.info("拷贝目标文件: {}",destinationFolder);
        }
    }

The basic idea is that I traverse directories and copy files.

Low back pain operation of directory

Younger martial sister: elder martial brother F, if I want to delete files in a directory, or we want to count how many files there are under this directory, what should I do?

Although these operations are a little painful, they can still be solved. There is a method in the files tool class called walk, which returns a stream object. We can use the stream API to process files.

Delete file:

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

Statistical file:

 public void useFileWalkToSumSize() 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);
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>