Create file in Java with all parent folders

Robin Sun :

In java any way to create a file without its parent foler and parent's parent folder

Here is the full path of the file to be created.D:\test3\ts435\te\util.log

There is not any folder existing in this path, which means there is nothing under D:\.

In java, when I create this file

File testFile=new File(filePath);
testFile.createNewFile();

It says it cannot find the path. Then I try to create the parent folder 'te'. Then it fail again, saying it cannot find the parent folder 'ts435'.

Is there any way to create the file forcely? To create the file with or without its parents and upper level folders exist.

Update 2019-06-28:

Hi guys, I finally find the reason. There are two mehtods, mkdir() and mkdirs(). When the destination folder's parent folder not exist, mkdir() will return false because it cannot forcely build the entire folder struncture.

However, mkdirs() can do this magic. It can build the entire folder chain whether parent folder exist or not.

Mushif Ali Nawaz :

You can ensure that parent directories exist by using this method File#mkdirs().

File f = new File("D:\\test3\\ts435\\te\\util.log");
f.getParentFile().mkdirs();
// ...

If parent directories don't exist then it will create them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127622&siteId=1