Create directories if not exists based on dot string package name

Viewed 295

I have got a package name, its value is com.foo.bar.my.app. I want to create the directories under src/main/test if any of the directory in the dot-based string package name does not exists.

I know I can achieve this by split each of the directory name:

String pkgName = "com.foo.bar.my.app";
String[] dirs = pkgName.split(".");

Then create File object for each directory name and use File#exists() api to check and create new file if not exists.

But is there a more concise elegant way to achieve it in Java 8 ?

3 Answers

It seems you're looking for Files.html#createDirectories, for example:

Files.createDirectories(Paths.get(pkgName.replaceAll("\\.", "/")));

From the Javadoc:

Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.

You can also use File.mkdirs to create any non existing nested directories

File file = new File(pkgName.replaceAll("\\.", "/"));

System.out.println(file.mkdirs());

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

Returns:

true if and only if the directory was created, along with all necessary parent directories; false otherwise

I think that the File.exist() method is java is the best way to check if a certain file is already existant on your computer.

Related