Retrieving information using the filesystem
suggest changeTo 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)
and
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
returnstrue
andnotExists
returnsfalse
in this case) - A file’s or directory’s nonexistence is verfied (
exists
returnsfalse
andnotExists
returnstrue
) - Neither the existence nor the nonexistence of a file or a directory can be verified (for example due to access restrictions): Both
exists
andnonExists
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 filestext/html
for HTML pagesapplication/pdf
for PDF filesimage/png
for PNG files
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents