Using Java nio to create a subdirectory and file
Solution 1
You could declare your confFile
as File
instead of Path
. Then you can use confFile.getParentFile().mkdirs();
, see example below:
// ...
File confFile = new File("./conf/conf.xml");
confFile.getParentFile().mkdirs();
// ...
Or, using your code as is, you can use:
Files.createDirectories(confFile.getParent());
Solution 2
You can create directory and file in one code line:
Files.createFile(Files.createDirectories(confDir).resolve(confFile.getFileName()))
Files.createDirectories(confDir)
will not throw an exception if the folder already exists and returns Path in any case.
user3341332
Updated on May 25, 2020Comments
-
user3341332 almost 4 years
I'm creating a simple program that will try to read in "conf/conf.xml" from disk, but if this file or dir doesn't exist will instead create them.
I can do this using the following code:
// create subdirectory path Path confDir = Paths.get("./conf"); // create file-in-subdirectory path Path confFile = Paths.get("./conf/conf.xml"); // if the sub-directory doesn't exist then create it if (Files.notExists(confDir)) { try { Files.createDirectory(confDir); } catch (Exception e ) { e.printStackTrace(); } } // if the file doesn't exist then create it if (Files.notExists(confFile)) { try { Files.createFile(confFile); } catch (Exception e ) { e.printStackTrace(); } }
My questions is if this really the most elegant way to do this? It seems superflous to need to create two Paths simple to create a new file in a new subdirectory.
-
user3341332 about 10 yearsWouldn't using mkdirs() or createDirectories(..) trip an exception if .conf/ already existed?I can see how it could be done with File, but wondered why the Paths/Files under nio didn't have an equally simply way to do this.
-
user207421 about 10 years@user3341332 No. It doesn't throw exceptions at all. See the Javadoc.
-
PhoneixS about 9 yearsBut note that
Path.getParent()
returnnull
if there is no more parts in the "string" of the Path. For example aPath
withdir/b.txt
will return pathdir
butdir.getParent()
will returnnull
. SoFiles.createDirectories(dir.getParent());
throw aNullPointerException
althoughdir
is inside other directory. -
Adam over 6 yearswhy go back to java.io.File when you're starting with java.nio.Path?
-
Adam over 6 years
-
mks-d over 3 years
Files.createDirectories(confDir)
will throw aFileAlreadyExistsException
, if the directory already exists. -
Valeriy K. over 3 years@mks-d I verified - run the code 2 times and don't get the exception. Which java version you use?
-
mks-d about 3 years@ValeriyK. good point. And my bad since it was with
createDirectory(Path)
and notcreateDirectories(Path)
. The version was ancient, Java 8.