Java IO & NIO - Files.notExists() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

public static boolean notExists(Path path,
                                LinkOption... options)

Tests whether the file located by this path does not exist.

Parameters:
path - the path to the file to test
options - options indicating how symbolic links are handled
Returns:
true if the file does not exist; false if the file exists or its existence cannot be determined


Examples


package com.logicbig.example.files;

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

public class NotExistsExample {

public static void main(String... args) {
Path path = Paths.get("d:\\my-test-file.txt");
boolean b = Files.notExists(path);
System.out.println(b);
}
}

Output

true




package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;

public class NotExistsExample2 {

public static void main(String... args) throws IOException {
Path dir = Files.createTempDirectory("test-dir");

Path path = dir.resolve("test-file.txt");
boolean srcNotExits = Files.notExists(path);
System.out.println("Source Not Exits: " + srcNotExits);

System.out.println("-- dir listing before Symbolic link created --");
Files.list(dir).forEach(System.out::println);

//following will fail if not run with admin privileges
Path symPath = Files.createSymbolicLink(dir.resolve("sym-" + path.getFileName()), path);

System.out.println("-- dir listing after Symbolic link created --");
Files.list(dir).forEach(System.out::println);

boolean symNotExits = Files.notExists(symPath);
System.out.println("Symbolic Link Not Exits: " + symNotExits);

symNotExits = Files.notExists(symPath, LinkOption.NOFOLLOW_LINKS);
System.out.println("Symbolic Link Not Exits with NOFOLLOW_LINKS OPTION: " + symNotExits);
}
}

Output

Source Not Exits: true
-- dir listing before Symbolic link created --
-- dir listing after Symbolic link created --
C:\Users\Joe\AppData\Local\Temp\test-dir11799549633540238985\sym-test-file.txt
Symbolic Link Not Exits: true
Symbolic Link Not Exits with NOFOLLOW_LINKS OPTION: false




See Also