Java Language New File I/O Retrieving information using the filesystem


To interact with the filesystem you use the methods of the class Files.

Checking existence

To check the existence of the file or directory a path points to, you use the following methods:

Files.exists(Path path)


Files.notExists(Path path)

!Files.exists(path) does not neccesarily have to be equal to Files.notExists(path), because there are three possible scenarios:

  • A file's or directory's existence is verified (exists returns true and notExists returns false in this case)
  • A file's or directory's nonexistence is verfied (exists returns false and notExists returns true)
  • Neither the existence nor the nonexistence of a file or a directory can be verified (for example due to access restrictions): Both exists and nonExists return false.

Checking whether a path points to a file or a directory

This is done using Files.isDirectory(Path path) and Files.isRegularFile(Path path)

Path p1 = Paths.get("/var/www");
Path p2 = Paths.get("/home/testuser/File.txt");
Files.isDirectory(p1) == true
Files.isRegularFile(p1) == false

Files.isDirectory(p2) == false
Files.isRegularFile(p2) == true

Getting properties

This can be done using the following methods:

Files.isReadable(Path path)
Files.isWritable(Path path)
Files.isExecutable(Path path)

Files.isHidden(Path path)
Files.isSymbolicLink(Path path)

Getting MIME type

Files.probeContentType(Path path)

This tries to get the MIME type of a file. It returns a MIME type String, like this:

  • text/plain for text files
  • text/html for HTML pages
  • application/pdf for PDF files
  • image/png for PNG files