java files

Java check if file exists

public static boolean exists(Path path, LinkOption… options)
Tests whether a file exists.
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.

Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security sensitive applications.

Parameters:
path – the path to the file to test
options – options indicating how symbolic links are handled .
Returns:
true if the file exists; false if the file does not exist or its existence cannot be determined.
Throws:
SecurityException – In the case of the default provider, the SecurityManager.checkRead(String) is invoked to check read access to the file.

package com.candidjava.filenio;

import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileExists {
  public static void main(String[] args) {
    Path path=Paths.get("F:/Filesnio/create.txt");
    boolean result;
    try {
      result=Files.exists(path,LinkOption.NOFOLLOW_LINKS);
      if(result)
      {
        System.out.println("File exists");
      }
      else
      {
        System.out.println("File doesnot exists");
      }
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
  }

}

Old Approach

public boolean exists()
Tests whether the file or directory denoted by this abstract pathname exists.
Returns:
true if and only if the file or directory denoted by this abstract pathname exists; false otherwise
Throws:
SecurityException – If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file or directory

package com.candidjava.file;

import java.io.File;

public class FileExists {
  public static void main(String[] args) {
    File file = new File("F:/Files/sample.txt");
    boolean result = file.exists();
    System.out.println(result);
    if (result) {
      System.out.println("File exists");

    } else {

      System.out.println("File doesn't exist");
    }
  }
}