Java.. Using NIO Class to get File information

Interfaces Path and DirectoryStream and classes Paths and Files (all from package java.nio.file) are useful for retrieving information about files and directories on disk.

Path interface—Objects of classes that implement Path represent the location of
a file or directory. 
Paths class—Provides static methods used to get a Path object representing a
file or directory location.
Files class—Provides static methods for common file and directory manipulations,
such as copying files; creating and deleting files and directories;
DirectoryStream interface—Objects of classes that implement this interface enable
a program to iterate through the contents of a directory.

Example:

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class FileAndDirectoryInfo {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("Enter file or directory name:");

// create Path object based on user input
Path path = Paths.get(input.nextLine());

if ( Files.exists(path)) {
System.out.printf("%n%s exists%n", path.getFileName());
System.out.printf("%s a directory%n",Files.isDirectory(path)? "Is" : "Is not");

System.out.printf("%s an absolute path%n", path.isAbsolute() ? "Is" : "Is not");

System.out.printf("Last modified: %s%n",Files.getLastModifiedTime(path));

System.out.printf("Size: %s%n",Files.size(path));
System.out.printf("Path: %s%n",path);
System.out.printf("Absolute path: %s%n",path.toAbsolutePath());

if (Files.isDirectory(path) ) {
System.out.printf("%nDirectory contents:%n");

// object for iterating through a directory's contents
DirectoryStream<Path> directoryStream =
Files.newDirectoryStream(path);

for (Path p : directoryStream){
System.out.println(p);
}
}
}
else { // not file or directory, output error message
System.out.printf("%s does not exist%n", path);
}
} // end main
} // end class 
Enter file or directory name:
c:\examples\demo
demo exists
Is a directory
Is an absolute path
Last modified: 2021-11-08T19:50:00.838256Z
Size: 4096
Path: c:\examples\demo
Absolute path: c:\examples\demo
Directory contents:
C:\examples\demo\d1
C:\examples\demo\d2
C:\examples\demo\d3
C:\examples\demo\d4
Enter file or directory name:
C:\examples\demo\d1\FileAndDirectoryInfo.java
FileAndDirectoryInfo.java exists
Is not a directory
Is an absolute path
Last modified: 2021-11-08T19:59:01.848255Z
Size: 2952
Path: C:\examples\demo\d1\FileAndDirectoryInfo.java
Absolute path: C:\examples\demo\d1\FileAndDirectoryInfo.java

Leave a Comment

Your email address will not be published. Required fields are marked *