Java IO & NIO - Files.isRegularFile() 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 isRegularFile(Path path,
                                    LinkOption... options)

Tests whether a file is a regular file.

Parameters:
path - the path to the file
options - options indicating how symbolic links are handled
Returns:
true if the file is a regular file; false if the file does not exist, is not a regular file, or it cannot be determined if the file is a regular file or not.


Examples


package com.logicbig.example.files;

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

public class IsRegularFileExample {

public static void main(String... args) throws IOException {
Path tempFile = Files.createTempFile("test-file", ".txt");
boolean regularFile = Files.isRegularFile(tempFile);
System.out.println("file: " + tempFile);
System.out.println("exits: " + Files.exists(tempFile));
System.out.println("regular: " + regularFile);
}
}

Output

file: C:\Users\Joe\AppData\Local\Temp\test-file12861011115215866627.txt
exits: true
regular: true




package com.logicbig.example.files;

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

public class IsRegularFileExample2 {

public static void main(String... args) throws IOException {
Path tempFile = Files.createTempDirectory("test-dir");
boolean regularFile = Files.isRegularFile(tempFile);
System.out.println("file: " + tempFile);
System.out.println("exits: " + Files.exists(tempFile));
System.out.println("regular: " + regularFile);
}
}

Output

file: C:\Users\Joe\AppData\Local\Temp\test-dir5244852189374751685
exits: true
regular: false




Following must run with admin privileges

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 IsRegularFileExample3 {

public static void main(String... args) throws IOException {
Path dir = Files.createTempDirectory("test-dir");
Path path = Files.createTempFile(dir, "test-file", ".txt");
//this will fail if not run with admin privileges
Path symPath = Files.createSymbolicLink(dir.resolve("sym-" + path.getFileName()), path);
boolean regularFile = Files.isRegularFile(symPath);
System.out.println("symPath regular: " + regularFile);

regularFile = Files.isRegularFile(symPath, LinkOption.NOFOLLOW_LINKS);
System.out.println("symPath with NOFOLLOW_LINKS option regular: " + regularFile);
}
}

Output

symPath regular: true
symPath with NOFOLLOW_LINKS option regular: false




See Also