The Path and Files Classes

Subdecks (1)

Cards (28)

  • The Path class creates objects that contain information about files and directories, such as sizes, locations, creation dates, and is used to check whether a file or directory exists.
  • The Files class performs operation on files and directories, such as determining their attributes, creating input and output streams, and deleting them.
  • To use both the Path and Files classes, add the following statement.
    import java.nio.file.*;
  • To create and define a Path, use Paths class and its get() method.
    Example: Path filePath = Paths.get("C:\\Java\\Chapter8\\sample.txt")
  • A absolute path is a complete path; it does not require any other information to locate a file on a system.
  • Example of absolute file: C:\Java\Chapter8\sample.txt
  • A relative path depends on other path information
  • Examples of relative path: sample.txt, Chapter8\sample.txt, Java\Chapter8.
  • To convert a relative path to an absolute path, the toAbsolutePath() method is used.
  • To verify if a file exists and if a program can access it when needed, the checkAccess() method is used.
  • The delete() method of the Files class accepts a Path parameter and removes the last element (file or directory) in a path or throws an exception if the deletion is unsuccessful.
  • file does not exists = NoSuchFileException
  • attempt to delete = DirectoryNotEmptyException
  • attempt to delete without permission = SecurityException
  • other input/output error cause IOException
  • deleteIfExists() - remove a file without encountering an exception if the file does not exists.
  • readAttributes() - To retrieve useful information.
  • readAttributes() returns an instance of the BasicFileAttributes.class.
  • Example of readAttributes():
    BasicFileAttributes fileAtt = Files.readAttributes(filePath, BasicAttributes.class);
  • size() = returns the size of a file
  • creationTime() = returns the date and time
  • Format of creationTime():
    yyyy-mm-ddThh:mm:ss
  • lastModifiedTime() = returns the time and date the file was last edited.
  • compareTo() = compares relationship between values retrieved from creationTime() or lastModifiedTime().