3

I want to check the Folder Existance before creating the new one. For that which method I need to use :

File folder = new File(PATH);

there are two method for checking the same
1) folder.getAbsoluteFile().exists() OR
2) folder.exists()

Which one to use?

Thanks for looking here.

mcacorner
  • 1,304
  • 3
  • 22
  • 45

5 Answers5

3

Under normal circumstances, there is no difference between the result of those two expressions. So, use the simpler:

folder.exists()
Joe
  • 29,416
  • 12
  • 68
  • 88
2

First of all read Oracle docs on exists. And getAbsoluteFile.

Answer yourself what does getAbsoluteFile do? Then answer yourself do you need to get the absolute form of of your folder abstract pathname? Does it help you in anything?

If not, use simpliest easy to write easy to read method folder.exists().

In coding we are always trying not to do unneccesary thing, to keep our code fast, clean, readable, easy to understand and update.

Adonis
  • 4,670
  • 3
  • 37
  • 57
Alexander Arutinyants
  • 1,619
  • 2
  • 23
  • 49
1

Generally calling folder.exists() is preferred as it works on abstract pathname.

On the otherhand getAbsoluteFile() is equivalent to new File(this.getAbsolutePath()), which returns the absolute form of this abstract pathname.

nitishagar
  • 9,038
  • 3
  • 28
  • 40
0

You can use both conditions as well.

Additionally You can refer this link..

How to create a file -- including folders -- for a given path?

Hope this will help !

Community
  • 1
  • 1
Vignesh Shiv
  • 1,129
  • 7
  • 22
0

folder.exist() check if the directory exist at the abstract path, it returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.

folder.getAbsoluteFile().exists() in this case it returns the absolute form of this abstract pathname. Equivalent to new File(this.getAbsolutePath()).exist() and checks if folder exists at specified absolute path.

so you can use either of them, just the difference is abstract path and absolute path, but to my openion you should go with folder.exist() since it will avoid creating new File.

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93