Jiew Meng
Jiew Meng

Reputation: 88337

Getting a file object of a directory

I need a File object pointing to a directory (may not be existing). How do I do that?

Even if I do something like

File dir = new File("/tmp/something/"); // with trailing slash

dir.isDirectory() is false. Then I tried dir.mkdir() which returns false, why? I dont need the directory to be existing, in fact, I want it to point to a directory that does not exist (I am doing testing). How can I achieve this?

Upvotes: 0

Views: 167

Answers (3)

AlfredoCasado
AlfredoCasado

Reputation: 818

from javadoc: "true if and only if the file denoted by this abstract pathname exists and is a directory"

If the file does not exists isDirectory() return false. If you are doing testing probably use a stub can be a better option, in unit testing its better try to don't touch external resources like the filesystem.

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136112

Trailing slash does not matter. File.isDirectory returns false because it returns true if and only if the file denoted by this abstract pathname exists and is a directory

Upvotes: 0

Kick
Kick

Reputation: 4923

Use dir.mkdirs()

mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.

Upvotes: 0

Related Questions