# Better way to create directories using File

I have this code that generally creates directories within a directory.

File  userFolder = new File(rootPath+"/media/"+userBean.getUsername());
userFolder.mkdir();
userPhotosDir.mkdir();
userAudioDir.mkdir();


When I this code runs it will generally look like this

The userFolder

\media\somename


The Photos folder

\media\somename\photos


The Audio Folder

\media\somename\folder


Where the photos and audio folder are inside the somename folder. while the somename folder is inside the media folder

-
what is the question? – tb- Jan 25 '13 at 18:14

Well, for the purpose of codereview:

• There is a mkdirs() methods instead of the mkdir() method
• You can use the new File(String, String) constructor to avoid taking care of slashes
• If you have Java7, you can (and probably should) use Path. Especially, because there is a way to construct Paths with unlimited arguments, not only 2 as for File:

Path dir = Paths.get(rootPath, "media", userBean.getUsername(), arg1);
Files.createDirectories(dir);

• You should check the return codes and errors. Could be helpful.

-

My main concern would be dealing with file path separators to construct long file paths. Luckily Java has File.separator which can be used to to manually construct paths. However try not to use them if necessary, and get the File objects to do the path creation for you.

String rootPath = "/";
File root = new File(rootPath);