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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With