Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file in Java with all parent folders [duplicate]

Tags:

java

file

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.

like image 865
Robin Sun Avatar asked Jan 26 '23 03:01

Robin Sun


1 Answers

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.

like image 101
Mushif Ali Nawaz Avatar answered Feb 02 '23 12:02

Mushif Ali Nawaz