Junior sister learning java IO: file file system

brief introduction

Younger martial sister has encountered another problem. This time, the problem is about file creation, file permissions and file system. Fortunately, the answers to these questions are in my mind. Let's have a look.

File permissions and file systems

As soon as I arrived at the company in the morning, my younger martial sister came up to me and asked me mysteriously: Senior brother F, I put some important files on the server, which are very, very important. Is there any way to protect it and give consideration to some privacy?

What document is so important? It won't be your picture. Don't worry, no one will be interested.

The younger martial sister said: of course not. I want to put my learning experience on it, but elder martial brother F, you know, I just started learning. Many ideas are not mature. I want to keep them secret first and then make them public later.

Seeing that younger martial sister is so self-motivated, I burst into tears and felt very comforted. Let's start.

You know, there are two types of operating systems in the world, windows and Linux (Unix). The two systems are very different, but both systems have a file concept. Of course, the range of files in Linux is wider, and almost all resources can be regarded as files.

If there are files, there are corresponding file systems. These file systems are supported by the system kernel. We don't need to make wheels repeatedly in Java programs. We can directly call the kernel interface of the system.

Younger martial sister: elder martial brother F, I understand this. We don't build wheels repeatedly. We are just wheel porters. So how does Java call the system kernel to create files?

The most common method to create a file is to call the createnewfile method in the file class. Let's see the implementation of this method:

public boolean createNewFile() throws IOException {
        SecurityManager security = System.getSecurityManager();
        if (security != null) security.checkWrite(path);
        if (isInvalid()) {
            throw new IOException("Invalid file path");
        }
        return fs.createFileExclusively(path);
    }

Method. If the security detection is passed, the createfileexclusive method of filesystem will be called to create the file.

In my Mac environment, the implementation class of file system is unixfilesystem:

public native boolean createFileExclusively(String path)
        throws IOException;

Did you see? Createfileexclusively in unixfilesystem is a native method that calls the underlying system interface.

Younger martial sister: Wow, after the file is created, we can assign permissions to the file, but are the permissions of windows and Linux the same?

Good question. Java code is cross platform. Our code needs to be executed in the JVM on windows and Linux at the same time, so we must find the common ground of their permissions.

Let's first look at the permissions of Windows files:

You can see that the permissions of a Windows file can be modified, read and execute. We don't need to consider the special permissions first, because we need to find the common ground between windows and Linux.

Let's look at the permissions of Linux files:

 ls -al www.flydean.com 
-rw-r--r--  1 flydean  staff  15 May 14 15:43 www.flydean.com

Above, I used an ll command to list www.flybean.com Com details of this file. The first column is the permission of the file.

The basic file permissions of Linux can be divided into three parts: owner, group and others. Like windows, each part has read, write and execute permissions, which are represented by RWX respectively.

The permissions of the three parts are connected to become rwxrwxrwx. Compared with our output results above, we can see www.flybean.com COM is readable and writable to the owner, read-only to group users, and read-only to other users.

If you want to make the file readable only to yourself, you can execute the following command:

chmod 600 www.flydean.com

The younger martial sister was immediately excited: elder martial brother F, I understand this. 6 is 110600 in binary and 110000000 in binary. It just corresponds to RW -------.

I am very satisfied with the comprehension ability of younger martial sister.

File creation

Although we are no longer Kong Yiji's era and do not need to know the four writing methods of fennel characters, it is very necessary to have more knowledge and more ways and make adequate preparations.

Younger martial sister, do you know how to create files in Java?

Younger martial sister whispered: Senior brother F, I only know a new file method.

I stroked my beard with satisfaction to show my master's aura.

As we mentioned earlier, IO has three categories: reader / writer, InputStream / OutputStream, and objectreader / objectwriter.

In addition to using the first new file, we can also use OutputStream. Of course, we also need to use the try with resource feature mentioned earlier to make the code more concise.

First look at the first way:

public void createFileWithFile() throws IOException {
        File file = new File("file/src/main/resources/www.flydean.com");
        //Create the file
        if (file.createNewFile()){
            log.info("恭喜,文件创建成功");
        }else{
            log.info("不好意思,文件创建失败");
        }
        //Write Content
        try(FileWriter writer = new FileWriter(file)){
            writer.write("www.flydean.com");
        }
    }

Look at the second way:

public  void createFileWithStream() throws IOException
    {
        String data = "www.flydean.com";
        try(FileOutputStream out = new FileOutputStream("file/src/main/resources/www.flydean.com")){
            out.write(data.getBytes());
        }
    }

The second approach looks more brief than the first.

Younger martial sister: wait, senior brother F, NiO has already appeared in JDK7. Can you use NiO to create files?

Of course, this problem is not difficult for me:

public void createFileWithNIO()  throws IOException
    {
        String data = "www.flydean.com";
        Files.write(Paths.get("file/src/main/resources/www.flydean.com"),data.getBytes());

        List<String> lines = Arrays.asList("程序那些事","www.flydean.com");
        Files.write(Paths.get("file/src/main/resources/www.flydean.com"),lines,StandardCharsets.UTF_8,StandardOpenOption.CREATE,StandardOpenOption.APPEND);
    }

NiO provides the files tool class to write files. When writing, we can also take some parameters, such as character coding, whether to replace the file or append to the back of the file, etc.

Permissions for files in code

Younger martial sister has another problem: elder martial brother F, after talking for a long time, he hasn't told me about authority.

Don't worry, let's talk about permissions now:

public void fileWithPromission() throws IOException {
        File file = File.createTempFile("file/src/main/resources/www.flydean.com","");
        log.info("{}",file.exists());

        file.setExecutable(true);
        file.setReadable(true,true);
        file.setWritable(true);
        log.info("{}",file.canExecute());
        log.info("{}",file.canRead());
        log.info("{}",file.canWrite());

        Path path = Files.createTempFile("file/src/main/resources/www.flydean.com",Files.exists(path));
        log.info("{}",Files.isReadable(path));
        log.info("{}",Files.isWritable(path));
        log.info("{}",Files.isExecutable(path));
    }

As we mentioned above, the JVM can only use the functions of both windows and Linux for general use, that is, the permissions are only read-write and execution permissions. Because the user or other users can also be distinguished in windows, the permissions of the user are also reserved.

In the above example, we use the traditional file and files in NiO to update the file permissions.

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
分享
二维码
< <上一篇
下一篇>>