3
\$\begingroup\$

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

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\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

palacsint
30.3k9 gold badges82 silver badges157 bronze badges
asked Jan 25, 2013 at 10:55
\$\endgroup\$
1
  • \$\begingroup\$ what is the question? \$\endgroup\$ Commented Jan 25, 2013 at 18:14

2 Answers 2

2
\$\begingroup\$

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.

palacsint
30.3k9 gold badges82 silver badges157 bronze badges
answered Jan 25, 2013 at 18:26
\$\endgroup\$
1
\$\begingroup\$

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 = "/";
String username = "tom";
String mediaDir = "media"
File root = new File(rootPath);
File userFolder = new File(root, mediaDir + File.separator + username);
File photos = new File(userFolder, "photos");
File tracks = new File(userFolder, "tracks");
if (photos.isFile()) {
 // delete it? Do something...
}
if (!photos.exists()) {
 photos.mkdirs();
}

Like tb- suggests in his answer, if you have Java 7 you may also want to look into Paths, Path and Files

answered Jan 26, 2013 at 12:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.