package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ExistsExample {
public static void main(String... args) throws IOException {
Path path = Files.createTempFile("test-file", ".txt");
System.out.println("File to check: " + path);
boolean exists = Files.exists(path);
System.out.println("File to check exits: " + exists);
//delete
Files.delete(path);
boolean existsNow = Files.exists(path);
System.out.println("File exits after deleting: " + existsNow);
}
}
Output
File to check: C:\Users\Joe\AppData\Local\Temp\test-file9149313535191257079.txt
File to check exits: true
File exits after deleting: false
Using LinkOption.NOFOLLOW_LINKS. This option will not check if this sym linked file's source exits or not.
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 ExistsExample2 {
public static void main(String... args) throws IOException {
Path tempDirectory = Files.createTempDirectory("test-dir");
Path path = Files.createTempFile(tempDirectory, "test-file", ".txt");
//creating a symbolic link
Path symbolicLink = Files.createSymbolicLink(path.getParent().resolve("sym-linked-file"), path);
System.out.println("Sym file: " + symbolicLink);
boolean exists = Files.exists(symbolicLink);
System.out.println("Sym File exits: " + exists);
//delete source
Files.delete(path);
//without any LinkOption
boolean existsNow = Files.exists(symbolicLink);
System.out.println("Sym file exits after deleting source file: " + existsNow);
//with LinkOption.NOFOLLOW_LINKS
boolean exitsNoFollowLink = Files.exists(symbolicLink, LinkOption.NOFOLLOW_LINKS);
System.out.println("Sym file exits with NOFOLLOW_LINKS option: " + exitsNoFollowLink);
}
}
Output
Sym file: C:\Users\Joe\AppData\Local\Temp\test-dir1768863456915673435\sym-linked-file
Sym File exits: true
Sym file exits after deleting source file: false
Sym file exits with NOFOLLOW_LINKS option: true