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
probeContentTypemethod 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
probeContentTypereturns 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-javabased on the.classextension, it may be fooled.You may provide a custom
FileTypeDetectorif the default is not sufficient for your needs.The
example uses theprobeContentTypemethod.
The Default File System
To get the default file system, use the
getDefaultmethod. Typically, thisFileSystemsmethod (note the plural) is chained to one of theFileSystemmethods (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 thePathseparator for the default file system you can use one of the following approaches:
String separator = File.separator; String separator = FileSystems.getDefault().getSeparator();The
getSeparatormethod 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
getFileStoresmethod. This method returns anIterablewhich 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
getFileStoremethod in thePathclass:
Path file = ...; FileStore store= file.getFileStore();The
DiskUsageexample uses thegetFileStoresmethod.