Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java java.nio.file.Files exists() Method

Java java.nio.file.Files exists() Method

Java File Java java.nio.file.Files

java.nio.file.Files.exists() method is a very practical utility method in the Java NIO (New I/O) package for checking whether a file or directory at the specified path exists. In daily development, an existence check before file operations is a common need, and exists() method provides a simple and efficient solution for this.

Method Definition

Files.exists() The method has the following two overloaded forms:

Basic form:

public

static

boolean

exists

(

Path path

)

The form with LinkOption:

Example

public

static

boolean

exists

(

Path path, LinkOption...

options

)

Parameter Description

Path path

LinkOption... options

- `LinkOption.NOFOLLOW_LINKS`: Do not follow symbolic links

Return Value

- `true`: If the file/directory exists - `false`: If the file/directory does not exist - If it cannot be determined whether the file exists (e.g., due to permission issues), an exception may be thrown

Usage examples

Basic Usage

Example

import

java.nio.file.*

;

public

class

FileExistsExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        Path filePath

=

Paths.

get

(

"test.txt"

)

;

       

       

if

(

Files.

exists

(

filePath

)

)

{

           

System

.

out

.

println

(

"File exists"

)

;

       

}

else

{

           

System

.

out

.

println

(

"File does not exist"

)

;

       

}

   

}

}

Check whether a directory exists

Example

Path dirPath

=

Paths.

get

(

"/path/to/directory"

)

;

if

(

Files.

exists

(

dirPath

)

)

{

   

System

.

out

.

println

(

"Directory exists"

)

;

}

Using LinkOption to not follow symbolic links

Example

Path symlinkPath

=

Paths.

get

(

"/path/to/symlink"

)

;

if

(

Files.

exists

(

symlinkPath, LinkOption.

NOFOLLOW_LINKS

)

)

{

   

System

.

out

.

println

(

"Symbolic link exists (target not checked)"

)

;

}


Notes

  1. Concurrency issues:

  2. Even if exists() Return true, the file may have been deleted by the time the subsequent operation runs
  3. For critical operations, it is recommended to perform the operation directly in a try-catch block rather than checking existence first
  4. - Even if `exists()` returns `true`, the file may have been deleted by the time the subsequent operation runs - For critical operations, it is recommended to perform the operation directly in a try-catch block rather than checking existence first
    1. Performance considerations:

    2. Multiple calls exists() may incur performance overhead
    3. For frequently checked scenarios, consider caching the result or using other mechanisms
    4. - Multiple calls to `exists()` may incur performance overhead - For frequently checked scenarios, consider caching the result or using other mechanisms
      1. Alternative methods:

      2. Files.notExists() Is exists() is the reverse method of
      3. For cases that need to create a file, you can use Files.createFile() method, which throws an exception when the file already exists
      4. - `Files.notExists()` is the reverse method of `exists()` - For cases that need to create a file, you can use `Files.createFile()` method, which throws an exception when the file already exists
        1. Exception handling:

        2. The method may throw SecurityException(if there is no access permission)
        3. Other I/O errors may also cause exceptions
        4. - The method may throw `SecurityException` (if there is no access permission) - Other I/O errors may also cause exceptions

          Comparison with Other Methods

          Method Description Difference
          File.exists() Existence check of the java.io.File class Old API, usually poorer performance
          Files.exists() NIO existence check More modern, supports more options
          Files.notExists() Check that a file does not exist The logic is reversed, but note the "unknown" state

          Best Practices

          Avoid redundant checks:

          Example

          // Not recommended

          if

          (

          Files.

          exists

          (

          path

          )

          )

          {

              Files.

          delete

          (

          path

          )

          ;

          }

             

          // Recommended

          try

          {

              Files.

          delete

          (

          path

          )

          ;

          }

          catch

          (

          NoSuchFileException e

          )

          {

             

          // Handle the case where the file does not exist

          }

          Combine with other checks:

          Example

          if

          (

          Files.

          exists

          (

          path

          )

          &&

          !

          Files.

          isDirectory

          (

          path

          )

          )

          {

             

          // Handle a regular file

          }

          Handle symbolic links correctly:

          Example

          // Check whether the symbolic link itself exists

          boolean

          linkExists

          =

          Files.

          exists

          (

          path, LinkOption.

          NOFOLLOW_LINKS

          )

          ;

             

          // Check whether the link target exists

          boolean

          targetExists

          =

          Files.

          exists

          (

          path

          )

          ;


          Summary

          Files.exists() method is a simple but important utility method in Java NIO file operations. It provides a standard way to check the existence of files/directories, supports symbolic link handling options, and is a modern replacement for traditional File.exists() solutions. In actual use, developers should be aware of its limitations, especially reliability issues in concurrent environments, and consider placing file operations directly in exception-handling blocks rather than relying on prior existence checks.

          Java File Java java.nio.file.Files