createNewFile File class () and mkdirs () mkdir ()

createNewFile file does not exist it is created, there is not created and returns false, the file path must exist before a file is created in the path (note that it can only create the file, that is, if you give / storage / emulated / 0 / hello / snow / such a path, it finally just create a folder in the snow hello unknown file instead of a folder, create a prerequisite for success described above or to / storage / emulated / 0 / hello / this folder path exists, If only / storage / emulated / 0 this folder path, it is not possible to create folders hello, so the failure to create) 

 

mkdirs () and mkdirs () is designed to create a folder, there is created returns true, false if present, can be the difference that mkdirs creating missing parent directories if necessary. The same path / storage / emulated / 0 / hello /snow.bin just created snow.bin folder instead of a file in a folder under ah hello.

 

It is generally required createNewFile () and mkdirs () is used in combination to create the folder and then create the file.

File file = new File(filePath);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();

}

mkdir: it can only be used to create folders, and you can only create a directory, if the parent does not exist, create failure.
mkdirs: can only be used to create folders, and can create multi-level directory, if the parent does not exist, it will be created automatically. (Create folders and more with this)
createNewFile: can only be used to create the file, and the file can only be created in the existing directory, otherwise it will create fail. (FileOutputStream os = new FileOutputStream (file ) You can also create files, look at the situation use)

Guess you like

Origin www.cnblogs.com/renjiaqi/p/11456358.html