其他有用的方法
一些有用的方法在本类的其他地方不适用,在此进行介绍。本节包括以下内容:
确定 MIME 类型
要确定文件的 MIME 类型,您可能会发现probeContentType(Path)方法很有用。例如:
try {
String type = Files.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);
}
请注意,如果无法确定 Content Type,则probeContentType
返回 null。
此方法的实现是高度特定于平台的,并且并非绝对可靠。Content Type 由平台的默认文件类型检测器确定。例如,如果检测器基于.class
extensions 将文件的 Content Type 确定为application/x-java
,则它可能会被欺骗。
如果默认值不足以满足您的需求,则可以提供自定义FileTypeDetector。
Email示例使用probeContentType
方法。
默认文件系统
要检索默认文件系统,请使用getDefault方法。通常,此FileSystems
方法(注意复数)链接到FileSystem
方法之一(注意单数),如下所示:
PathMatcher matcher =
FileSystems.getDefault().getPathMatcher("glob:*.*");
路径字符串 分隔符
POSIX 文件系统的路径分隔符为正斜杠/
,而对于 Microsoft Windows 则为反斜杠\
。其他文件系统可能使用其他定界符。要检索默认文件系统的Path
分隔符,可以使用以下方法之一:
String separator = File.separator;
String separator = FileSystems.getDefault().getSeparator();
getSeparator方法还用于检索任何可用文件系统的路径分隔符。
文件系统的文件存储
文件系统具有一个或多个文件存储来保存其文件和目录。 文件存储表示基础存储设备。在 UNIXos 中,每个已安装的文件系统都由一个文件存储表示。在 Microsoft Windows 中,每个卷都由一个文件存储表示:C:
,D:
等。
要检索文件系统的所有文件存储的列表,可以使用getFileStores方法。此方法返回Iterable
,它使您可以使用enhanced for语句遍历所有根目录。
for (FileStore store: FileSystems.getDefault().getFileStores()) {
...
}
如果要检索特定文件所在的文件存储,请使用Files
类中的getFileStore方法,如下所示:
Path file = ...;
FileStore store= Files.getFileStore(file);
DiskUsage示例使用getFileStores
方法。