snippetjavaMinor
Better way to create directories using File
Viewed 0 times
filecreatewaybetterusingdirectories
Problem
I have this code that generally creates directories within a directory.
When I this code runs it will generally look like this
The userFolder
The Photos folder
The Audio Folder
Where the photos and audio folder are inside the somename folder. while the somename folder is inside the media folder
File userFolder = new File(rootPath+"/media/"+userBean.getUsername());
File userPhotosDir = new File(rootPath+"/media/"+userBean.getUsername()+"/photos");
File userAudioDir = new File(rootPath+"/media/"+userBean.getUsername()+"/tracks");
userFolder.mkdir();
userPhotosDir.mkdir();
userAudioDir.mkdir();When I this code runs it will generally look like this
The userFolder
\media\somenameThe Photos folder
\media\somename\photosThe Audio Folder
\media\somename\folderWhere the photos and audio folder are inside the somename folder. while the somename folder is inside the media folder
Solution
Well, for the purpose of codereview:
-
If you have Java7, you can (and probably should) use
-
You should check the return codes and errors. Could be helpful.
- There is a
mkdirs()methods instead of themkdir()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.
Code Snippets
Path dir = Paths.get(rootPath, "media", userBean.getUsername(), arg1);
Files.createDirectories(dir);Context
StackExchange Code Review Q#20892, answer score: 2
Revisions (0)
No revisions yet.