Java: File.getAbsoluteFile (). exists () v / s File.exists ()

I want to check the Expression Folder before creating a new one. For this method, I have to use:

File folder = new File(PATH);

      

there are two methods for checking the same
1) folder.getAbsoluteFile().exists()

  OR
2)folder.exists()

Which one to use?

Thanks for looking here.

+3


source to share


5 answers


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

Answer yourself, what does it do getAbsoluteFile

? Then answer yourself: do you need to get the absolute form of the abstract path of your folder? Does it help you with anything?



If not, use the easiest, easiest-to-read reading method folder.exists()

.

In coding, we always try not to do anything fancy to keep our code fast, clean, readable, easy to understand and update.

+2


source


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



folder.exists()

      

+3


source


Usually calling folder.exists()

is preferred because it works for abstract pathname

.

On the other hand is getAbsoluteFile()

equivalent new File(this.getAbsolutePath())

, which returns the absolute form of this abstract path.

+1


source


You can also use both conditions.

Additionally you can refer to this link ..

How do I create a file - including folders - for a given path?

Hope this helps!

0


source


folder.exist()

check if the directory exists in the abstract path, it returns true if and only if the file or directory denoted by this abstract path exists; false otherwise.

folder.getAbsoluteFile().exists()

in this case, returns the absolute form of this abstract path. Equivalent to new File(this.getAbsolutePath()).exist()

and checks if the folder at the specified absolute path exists.

so you can use either of them, just the difference is an abstract path and an absolute path, but to my discovery you have to go with folder.exist()

since this will avoid creation new File

.

0


source







All Articles