Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a file or directory exists in Java

Tags:

java

file

exists

From this java tutorial by oracle:

Note that !Files.exists(path) is not equivalent to Files.notExists(path).

Why would they not be equivalent? it does not go any further in terms of explanation. Does anybody know more information about that? Thanks in advance!

like image 484
Rollerball Avatar asked Apr 30 '13 15:04

Rollerball


People also ask

How do you check if a path is a directory Java?

isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.

How do you check if a file already exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .

How do I find the path in Java?

Select Start, select Control Panel. double click System, and select the Advanced tab. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it.


2 Answers

!Files.exists() returns:

  • true if the file does not exist or its existence cannot be determined
  • false if the file exists

Files.notExists() returns:

  • true if the file does not exist
  • false if the file exists or its existence cannot be determined
like image 199
Adam Stelmaszczyk Avatar answered Sep 28 '22 10:09

Adam Stelmaszczyk


As we see from Files.exists the return result is:

TRUE if the file exists; 
FALSE if the file does not exist or its existence cannot be determined.

And from Files.notExists the return result is:

TRUE if the file does not exist; 
FALSE if the file exists or its existence cannot be determined

So if !Files.exists(path) return TRUE means it not exists or the existence cannot be determined (2 possibilities) and for Files.notExists(path) return TRUE means it not exists (just 1 possibility).

The conclusion !Files.exists(path) != Files.notExists(path) or 2 possibilities not equals to 1 possibility (see the explanation above about the possibilities).

like image 30
Crazenezz Avatar answered Sep 28 '22 12:09

Crazenezz