There are a few useful methods that did not fit elsewhere in this tutorial and are covered here. This section covers:
- Determining MIME Type
- The Default File System
- The Path String Separator
- The File System's File Stores
Determining MIME Type
To determine the MIME type of a file, you may find the
probeContentType
method useful. For example:
try { String type = File.probeContentType(filename); if (type == null) { System.err.format("'%s' has an unknown filetype.%n", filename); } else if (!type.equals("text/plain") { System.err.format("'%s' is not a plain text file.%n", filename); continue; } } catch (IOException x) { System.err.println(x); }Note that
probeContentType
returns null if the content type cannot be determined.The implementation of this method is highly platform specific and is not infallible. The content type is determind by the platform's default file type detector. For example, if the detector determines a file's content type to be
application/x-java
based on the.class
extension, it may be fooled.You may provide a custom
FileTypeDetector
if the default is not sufficient for your needs.The
example uses the
probeContentType
method.
The Default File System
To get the default file system, use the
getDefault
method. Typically, thisFileSystems
method (note the plural) is chained to one of theFileSystem
methods (note the singular), like this:
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.*");
The Path String Separator
The path separator for POSIX file systems is the backslash,
/
, and for Microsoft Windows is the forward slash,\
. Other file systems may use other delimiters. To get the thePath
separator for the default file system you can use one of the following approaches:
String separator = File.separator; String separator = FileSystems.getDefault().getSeparator();The
getSeparator
method is also used to retrieve the path separator for any available file system.
The File System's File Stores
A file system has one or more file stores to hold its files and directories. The file store represents the underlying storage device: on Microsoft Windows, each volume is represented by a file store:
C:
,D:
, and so on. On UNIX, each mounted file system is represented by a file store.To get a list of all the file stores for the file system, you can use the
getFileStores
method. This method returns anIterable
which allows you to use the enhanced for statement to iterate over all the root directories.
for (FileStore store: FileSystems.getDefault().getFileStores()) { ... }If you want to get the file store where a particular file is located, use the
getFileStore
method in thePath
class:
Path file = ...; FileStore store= file.getFileStore();The
DiskUsage
example uses thegetFileStores
method.