FileAndDirectoryInfo.java

c:\ece538\ch15\fig15_02>java FileAndDirectoryInfo
Enter file or directory name:
..\fig15_02

fig15_02 exists
Is a directory
Is not an absolute path
Last modified: 2020-01-31T17:00:51.763303Z
Size: 4096
Path: ..\fig15_02
Absolute path: c:\ece538\ch15\fig15_02\..\fig15_02

Directory contents:
..\fig15_02\FileAndDirectoryInfo.class
..\fig15_02\FileAndDirectoryInfo.java
..\fig15_02\FileAndDirectoryInfo.java.html


FileAndDirectoryInfo.java

// Fig. 15.2: FileAndDirectoryInfo.java
// File class used to obtain file and directory information.
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)) // if path exists, output info about it
      {
         // display file (or directory) information
      	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)) // output directory listing
         {
            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);
      }   
   }
} 


Maintained by John Loomis, updated Fri Jan 31 11:36:40 2020