The difference between file.mkdir(), file.mkdirs() and file.createNewFile()

file.mkdir() creates a single-level folder, file.mkdirs() creates a multi-level folder, and file.createNewFile() creates a file.
Let's verify it through a demo:

public class MainActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                File internalFile = getCacheDir();
                String internalPath = internalFile.getPath();
                File file1 = new File(internalPath,"demo1");
                File file2 = new File(internalPath,"demo2/demo");
                File file3 = new File(internalPath,"demo3/demo");
                File file4 = new File(internalPath+"/demo3","demo4");
                file2.mkdir();
                file3.mkdirs();
                file4.mkdir();
                try {
    
    
                    file1.createNewFile();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        });
    }
}

There is a button on the page layout. Click the button to create a file. Before clicking the button, take a look at the file directory of the application memory to know what happened in this process. The directory before clicking is as follows:

img

From the directory, we can see that there is only one folder and two files. After running the above program, let's take a look at the changes:

insert image description here

As can be seen from the figure, file1 calls the method file.createNewFile() to create a file; file2 is a multi-level directory that calls the file.mkdir() method and fails to create; file3 is also a multi-level directory that calls the method file.mkdirs( ) method is successfully created; file4 is compared with file2, and the method file.mkdir() is called to create a single-level folder with the parent directory of file3 as the parent directory; finally, we add two lines of code to see how to use file in multi-level directories. Whether the createNewFile() method can be successfully created:

File file5 = new File(internalPath,"demo5/demo");
file5.createNewFile();

insert image description here

After running the program, no new files or folders were found in the file directory.

Summary: file.mkdir() creates a single-level folder, and can only be created successfully if the parent directory exists; file.mkdirs() creates a multi-level folder, regardless of whether the parent directory exists; file.createNewFile( ) creates a file, and cannot be created successfully if the parent directory does not exist.

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/130072195